﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Xml;
using System.IO;
using System.Diagnostics;
using System.Globalization;
using PrintDataGrid;
using System.Configuration;
using System.Threading;

namespace ReportsApp
{
    public partial class Form1 : Form
    {
        private bool IsLoggedIn = false;

        DataTable dtBranches = null;
        DataTable dtBranchesAll = null;

        public string Branch { get; set; }
        public DateTime Date { get; set; }
        public bool IsMonthly { get; set; }
        private string tempBranch;

        //Variable used to remember the state
        private int BranchIndex = 0;
        private DateTime SelectedDate = DateTime.Now.AddDays(-1);
        private bool IsCheckedMontly = false;

        private double ApplicationCashAvailable = 0;
        private double ActualCashAvailable = 0;

        private string paymentSupplier = string.Empty;
        private string paymentBranch = string.Empty;
        private string paymentDate = string.Empty;

        private const int VERSION = 3;
        private const int APPID = 1;

        #region .Ctr
        public Form1()
        {
            InitializeComponent();

            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-IN");

            /*//Setting TimeLines to Operate the Application
            DateTime currentDate = GetCurrentDateTime();

            //June To Aug
            if (!(currentDate.Month >= 5 && currentDate.Month <= 7))
            {
                MessageBox.Show("Invalid Application Request!!! Contact Administrator.", "Invalid Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
                return;
            }*/

            //Validating the version
            if (!DBHelper.ValidateVersion(APPID, VERSION))
            {
                MessageBox.Show("Upgrade to Latest Version !", "Obsolete Version", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }

            //Disabling the Tab Control Headers
            tabMainCtrl.Appearance = TabAppearance.FlatButtons;
            tabMainCtrl.ItemSize = new Size(0, 1);
            tabMainCtrl.SizeMode = TabSizeMode.Fixed;

            dpDate.MaxDate = dpDateMonthly.MaxDate = dpRemainingStock.MaxDate = dtExpensesDate.MaxDate = dpDateCreditNotes.MaxDate = dpDateDamages.MaxDate = dtpCancelledBills.MaxDate = dtDiscount.MaxDate = dpDateBulk.MaxDate = dtpCakeReport.MaxDate = dtpLoginDate.MaxDate = dtpItemWise.MaxDate = dtpDeptWise.MaxDate = dpDateVendor.MaxDate = dtpSalesReportDate.MaxDate = DateTime.Now;
        }
        #endregion

        private void chkBranchConnect_CheckedChanged(object sender, EventArgs e)
        {
            //lblRemainingStockDate.Enabled = dpRemainingStock.Enabled = !(DBHelper.IsBranchData = chkBranchConnect.Checked);

            //if (!dpRemainingStock.Enabled)
            //{
            //    dpRemainingStock.Value = dtExpensesDate.Value = DateTime.Now;
            //}
            //else
            //{
            //    dpRemainingStock.Value = dtExpensesDate.Value = SelectedDate;
            //}
            DBHelper.IsBranchData = false;//chkBranchConnect.Checked;
        }

        #region Private Methods

        private DateTime GetCurrentDateTime()
        {
            try
            {
                WebRequest request = WebRequest.Create(@"http://developer.yahooapis.com/TimeService/V1/getTime?appid=Test");
                // request.Proxy = new WebProxy("PROXYSERVERNAME", 8080); // You may or may not need this 
                WebResponse response = request.GetResponse();

                Double currentTimeStamp = 0;
                using (Stream stream = response.GetResponseStream())
                {
                    using (XmlTextReader xmlReader = new XmlTextReader(stream))
                    {
                        while (xmlReader.Read())
                        {
                            switch (xmlReader.NodeType)
                            {
                                case XmlNodeType.Element:
                                    if (xmlReader.Name == "Timestamp")
                                    {
                                        currentTimeStamp = Convert.ToDouble(xmlReader.ReadInnerXml());
                                    }
                                    break;
                            }
                        }

                        xmlReader.Close();
                    }
                }

                DateTime yahooDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
                return yahooDateTime.AddSeconds(currentTimeStamp).AddHours(5).AddMinutes(30);
            }
            catch (Exception ex)
            {
                WriteToEventViewer("Couldn't get the current time from internet. " + ex.Message);
                return DateTime.Now;
            }
        }

        private void WriteToEventViewer(string message)
        {
            try
            {
                if (!EventLog.SourceExists("KSBakery"))
                    EventLog.CreateEventSource("KSBakery", "KSBakery");
                EventLog.WriteEntry("KSBakery", message, EventLogEntryType.Error);
            }
            catch (Exception)
            { }
        }

        #endregion

        #region Financial Report

        private void btnFinancialReport_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {

                try
                {
                    if (dtBranchesAll == null)
                    {
                        dtBranchesAll = DBHelper.GetBranches();
                        dtBranchesAll.Rows.Add(0, "All");
                    }
                    cmbBranch.DataSource = dtBranchesAll;
                    cmbBranch.DisplayMember = "BranchName";
                    cmbBranch.ValueMember = "BranchID";
                    tabMainCtrl.SelectTab(2);

                    cmbBranch.SelectedIndex = BranchIndex;
                    dpDate.Value = SelectedDate;
                    dgFinancialReport.DataSource = null;
                    dgvIndividualSales.DataSource = null;

                    lblPOSSales.Text = "POS Sales: ";
                    lblCakeSales.Text = "Cake Sales: ";
                    lblDiscount.Text = "Discount: ";
                    lblTotalSales.Text = "Total Sales: ";
                    lblExpenditure.Text = "Expenses: ";
                    lblSodexho.Text = "Sodexho Sales: ";
                    lblCard.Text = "Card Sales: ";
                    lblSalariesAppDetails.Text = "Emp Advance/Bill Amounts: ";
                    lblCreditNoteBills.Text = "Credit Note Amount: ";
                    lblCashAvailable.Text = "Cash Available: ";
                    lblBulkOrders.Text = "Bulk Orders: ";

                    lblCakeAdvances.Text = "Advances: ";
                    lblCakeIdealBalances.Text = "Ideal Balances: ";
                    lblCakeActualBalances.Text = "Actual Balances: ";

                    lblBulkOrderAdvances.Text = "Advances: ";
                    lblBulkOrderIdealBalances.Text = "Ideal Balances: ";
                    lblBulkOrderActualBalances.Text = "Actual Balances: ";
                }
                catch (Exception)
                {
                    MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabMainCtrl.SelectTab(22);
                txtUserNameUser.Focus();
            }
        }

        private void btnFetch_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                if (cmbBranch.SelectedValue.ToString() == "0" && chkBranchConnect.Checked)
                {
                    MessageBox.Show("Connecting to Branches cannot fetch Complete Data. Please change the Criteria.", "Invalid Criteria", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                Branch = cmbBranch.Text;
                Date = dpDate.Value;

                SelectedDate = dpDate.Value;

                dgFinancialReport.DataSource = null;
                dgvIndividualSales.DataSource = null;

                lblPOSSales.Text = "POS Sales: ";
                lblCakeSales.Text = "Cake Sales: ";
                lblDiscount.Text = "Discount: ";
                lblTotalSales.Text = "Total Sales: ";
                lblExpenditure.Text = "Expenses: ";
                lblSodexho.Text = "Sodexho Sales: ";
                lblCard.Text = "Card Sales: ";
                lblSalariesAppDetails.Text = "Emp Advance/Bill Amounts: ";
                lblCreditNoteBills.Text = "Credit Note Amount: ";
                lblCashAvailable.Text = "Cash Available: ";
                lblBulkOrders.Text = "Bulk Orders: ";

                lblCakeAdvances.Text = "Advances: ";
                lblCakeIdealBalances.Text = "Ideal Balances: ";
                lblCakeActualBalances.Text = "Actual Balances: ";
                
                lblBulkOrderAdvances.Text = "Advances: ";
                lblBulkOrderIdealBalances.Text = "Ideal Balances: ";
                lblBulkOrderActualBalances.Text = "Actual Balances: ";

                DataSet dsResult = DBHelper.GetFinancialReport(dpDate.Value, cmbBranch.SelectedValue.ToString());
                double cakeSales = 0d;

                double cakeAdvances = 0d;
                double cakeIdealBalances = 0d;
                double cakeActualBalances = 0d;

                double discounts = 0d;
                double totalSales = 0d;
                double expenseAmt = 0d;
                double sodexhoAmt = 0d;
                double creditCardAmt = 0d;
                double salariesAmt = 0d;
                double creditNoteAmount = 0d;
                double bulkOrderAmt = 0d;

                double boAdvances = 0d;
                double boIdealBalances = 0d;
                double boActualBalances = 0d;

                if (dsResult != null)
                {
                    //Empty Row
                    dsResult.Tables[0].Rows.Add(dsResult.Tables[0].NewRow());

                    //POS Sales
                    DataRow drSales = dsResult.Tables[0].NewRow();
                    drSales[1] = "POS SALES";
                    if (dsResult.Tables[1].Rows[0]["POSSales"] != System.DBNull.Value)
                    {
                        drSales[3] = dsResult.Tables[1].Rows[0]["POSSales"].ToString();
                    }
                    else
                    {
                        drSales[3] = 0;
                    }

                    dsResult.Tables[0].Rows.Add(drSales);

                    //Cake Sales
                    double tmpValue = 0d;

                    if (double.TryParse(dsResult.Tables[2].Rows[0]["Advance"].ToString(), out tmpValue))
                    {
                        double discount = 0d;
                        double.TryParse(dsResult.Tables[2].Rows[0]["CakeDiscounts"].ToString(), out discount);

                        cakeAdvances = tmpValue - discount;
                        cakeSales += tmpValue - discount;
                    }

                    if (double.TryParse(dsResult.Tables[3].Rows[0]["Balance"].ToString(), out tmpValue))
                    {
                        cakeIdealBalances = tmpValue;
                        //cakeSales += tmpValue;
                    }

                    if (dsResult.Tables[14] != null && dsResult.Tables[14].Rows.Count > 0)
                    {
                        double val = 0d;
                        foreach (DataRow row in dsResult.Tables[14].Rows)
                        {
                            double.TryParse(row["CakeBalances"].ToString(), out val);
                            cakeActualBalances += val;
                        }
                    }
                    cakeSales += cakeActualBalances;

                    DataRow drCakeSales = dsResult.Tables[0].NewRow();
                    drCakeSales[1] = "TOTAL CAKE SALES";
                    drCakeSales[3] = cakeSales.ToString();
                    dsResult.Tables[0].Rows.Add(drCakeSales);

                    DataRow drCakeAdvances = dsResult.Tables[0].NewRow();
                    drCakeAdvances[1] = "CAKE ADVANCES";
                    drCakeAdvances[3] = cakeAdvances.ToString();
                    dsResult.Tables[0].Rows.Add(drCakeAdvances);

                    DataRow drCakeIdealBalances = dsResult.Tables[0].NewRow();
                    drCakeIdealBalances[1] = "CAKE IDEAL BALANCES";
                    drCakeIdealBalances[3] = cakeIdealBalances.ToString();
                    dsResult.Tables[0].Rows.Add(drCakeIdealBalances);

                    DataRow drCakeActualBalances = dsResult.Tables[0].NewRow();
                    drCakeActualBalances[1] = "CAKE ACTUAL BALANCES";
                    drCakeActualBalances[3] = cakeActualBalances.ToString();
                    dsResult.Tables[0].Rows.Add(drCakeActualBalances);

                    //Vendor Sales
                    double vendorSales = 0d;

                    double.TryParse(dsResult.Tables[7].Rows[0]["VendorSales"].ToString(), out vendorSales);
                    DataRow drVendorSales = dsResult.Tables[0].NewRow();
                    drVendorSales[1] = "VENDOR SALES";
                    drVendorSales[3] = vendorSales.ToString();
                    dsResult.Tables[0].Rows.Add(drVendorSales);

                    //Bulk Orders
                    if (dsResult.Tables[8] != null && dsResult.Tables[8].Rows.Count > 0)
                    {
                        double.TryParse(dsResult.Tables[8].Rows[0]["BulkOrderAdvance"].ToString(), out tmpValue);
                        boAdvances = tmpValue;
                        bulkOrderAmt += tmpValue;
                    }

                    if (dsResult.Tables[9] != null && dsResult.Tables[9].Rows.Count > 0)
                    {
                        double.TryParse(dsResult.Tables[9].Rows[0]["BulkOrderBalance"].ToString(), out tmpValue);
                        boIdealBalances = tmpValue;
                        //bulkOrderAmt += tmpValue;
                    }

                    if (dsResult.Tables[16] != null && dsResult.Tables[16].Rows.Count > 0)
                    {
                        double val = 0d;
                        foreach (DataRow row in dsResult.Tables[16].Rows)
                        {
                            double.TryParse(row["Balance"].ToString(), out val);
                            boActualBalances += val;
                        }
                    }
                    bulkOrderAmt += boActualBalances;

                    DataRow drBulkOrder = dsResult.Tables[0].NewRow();
                    drBulkOrder[1] = "BULK ORDERS";
                    drBulkOrder[3] = bulkOrderAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drBulkOrder);

                    //Discount
                    tmpValue = 0d;

                    if (dsResult.Tables[1].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[1].Rows[0]["POSDiscounts"].ToString(), out tmpValue))
                            discounts += tmpValue;
                    }

                    double cakeDiscounts = 0d;
                    if (dsResult.Tables[2].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[2].Rows[0]["CakeDiscounts"].ToString(), out cakeDiscounts))
                            discounts += cakeDiscounts;
                    }

                    DataRow drDiscount = dsResult.Tables[0].NewRow();
                    drDiscount[1] = "DISCOUNT";
                    drDiscount[3] = discounts;
                    dsResult.Tables[0].Rows.Add(drDiscount);

                    //Total Sales
                    tmpValue = 0d;

                    if (dsResult.Tables[1].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[1].Rows[0]["POSSales"].ToString(), out tmpValue))
                        {
                            totalSales += tmpValue;
                        }
                    }
                    totalSales += cakeSales;
                    totalSales += vendorSales;
                    totalSales += bulkOrderAmt;
                    //totalSales += creditNoteAmount;

                    DataRow drTotalSales = dsResult.Tables[0].NewRow();
                    drTotalSales[1] = "TOTAL SALES";
                    drTotalSales[3] = (totalSales - discounts + creditNoteAmount).ToString();
                    dsResult.Tables[0].Rows.Add(drTotalSales);

                    //Expense Amounts
                    tmpValue = 0d;

                    if (dsResult.Tables[4].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[4].Rows[0]["ExpenseAmount"].ToString(), out tmpValue))
                            expenseAmt = tmpValue;
                    }

                    DataRow drExpense = dsResult.Tables[0].NewRow();
                    drExpense[1] = "EXPENSE AMOUNT";
                    drExpense[3] = expenseAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drExpense);

                    //Sodexho Amount
                    tmpValue = 0d;

                    if (dsResult.Tables[5].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[5].Rows[0]["SodexhoAmount"].ToString(), out tmpValue))
                            sodexhoAmt = tmpValue;
                    }

                    DataRow drSodexho = dsResult.Tables[0].NewRow();
                    drSodexho[1] = "SODEXHO AMOUNT";
                    drSodexho[3] = sodexhoAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drSodexho);

                    //CreditCard Amount
                    tmpValue = 0d;

                    if (dsResult.Tables[5].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[5].Rows[0]["CreditCardAmount"].ToString(), out tmpValue))
                            creditCardAmt = tmpValue;
                    }

                    DataRow drCard = dsResult.Tables[0].NewRow();
                    drCard[1] = "CREDITCARD AMOUNT";
                    drCard[3] = creditCardAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drCard);

                    //Get Advances & Bill from Salaries Application - By Cashier
                    //salariesAmt = DBHelper.GetEmpAdvancesandBills(dpDate.Value, cmbBranch.SelectedValue.ToString());
                    DataSet dsAdvancesAndBills = DBHelper.GetEmpAdvancesandBills(dpDate.Value, cmbBranch.SelectedValue.ToString());
                    try
                    {
                        salariesAmt = double.Parse(dsAdvancesAndBills.Tables[0].Rows[0]["EmployeeDebitAmount"].ToString());
                    }
                    catch (Exception)
                    {
                        salariesAmt = 0d;
                    }

                    DataRow drSalariesApp = dsResult.Tables[0].NewRow();
                    drSalariesApp[1] = "EMP ADVANCES/BILLS";
                    drSalariesApp[3] = salariesAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drSalariesApp);

                    //Credit Note Amount
                    if (dsResult.Tables[6].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[6].Rows[0]["CreditNoteAmount"].ToString(), out tmpValue))
                            creditNoteAmount = tmpValue;
                    }

                    DataRow drCreditNoteAmount = dsResult.Tables[0].NewRow();
                    drCreditNoteAmount[1] = "CREDIT NOTES AMOUNT";
                    drCreditNoteAmount[3] = creditNoteAmount;
                    dsResult.Tables[0].Rows.Add(drCreditNoteAmount);

                    //Available Cash
                    DataRow drAvailableCash = dsResult.Tables[0].NewRow();
                    drAvailableCash[1] = "AVAILABLE CASH";
                    //drAvailableCash[3] = Math.Round(totalSales - discounts - expenseAmt - sodexhoAmt - creditCardAmt - salariesAmt - creditNoteAmount, 2);
                    drAvailableCash[3] = Math.Round(totalSales - discounts - expenseAmt - sodexhoAmt - creditCardAmt - salariesAmt, 2);
                    dsResult.Tables[0].Rows.Add(drAvailableCash);

                    dgFinancialReport.DataSource = dsResult.Tables[0];
                    dgFinancialReport.Columns[0].Width = 80;
                    dgFinancialReport.Columns[1].Width = 170;
                    dgFinancialReport.Columns[2].Width = 70;
                    dgFinancialReport.Columns[3].Width = 100;

                    lblPOSSales.Text = "POS Sales: " + dsResult.Tables[1].Rows[0]["POSSales"].ToString();
                    lblCakeSales.Text = "Cake Sales: " + cakeSales.ToString();

                    lblCakeAdvances.Text = "Advances: " + cakeAdvances.ToString();
                    lblCakeIdealBalances.Text = "Ideal Balances: " + cakeIdealBalances.ToString();
                    lblCakeActualBalances.Text = "Actual Balances: " + cakeActualBalances.ToString();

                    lblDiscount.Text = "Discount: " + discounts.ToString();
                    lblTotalSales.Text = "Total Sales: " + (totalSales - discounts + creditNoteAmount).ToString();
                    lblExpenditure.Text = "Expenses: " + expenseAmt.ToString();
                    lblSodexho.Text = "Sodexho Sales: " + sodexhoAmt.ToString();
                    lblCard.Text = "Card Sales: " + creditCardAmt.ToString();
                    lblSalariesAppDetails.Text = "Emp Advance/Bill Amounts: " + salariesAmt.ToString();
                    lblCreditNoteBills.Text = "Credit Note Amount: " + creditNoteAmount.ToString();
                    //ApplicationCashAvailable = Math.Round(totalSales - discounts - expenseAmt - sodexhoAmt - creditCardAmt - salariesAmt - creditNoteAmount, 2);
                    ApplicationCashAvailable = Math.Round(totalSales - discounts - expenseAmt - sodexhoAmt - creditCardAmt - salariesAmt, 2);
                    lblCashAvailable.Text = "Cash Available: " + ApplicationCashAvailable.ToString();

                    lblBulkOrders.Text = "Bulk Orders: " + bulkOrderAmt.ToString();

                    lblBulkOrderAdvances.Text = "Advances: " + boAdvances.ToString();
                    lblBulkOrderIdealBalances.Text = "Ideal Balances: " + boIdealBalances.ToString();
                    lblBulkOrderActualBalances.Text = "Actual Balances: " + boActualBalances.ToString();

                    if (cmbBranch.SelectedValue.ToString() != "0")
                    {
                        BranchIndex = cmbBranch.SelectedIndex;
                        DataRow drRow = DBHelper.GetActualAmount(dpDate.Value, cmbBranch.SelectedValue.ToString());
                        if (drRow != null)
                        {
                            ActualCashAvailable = double.Parse(drRow[0].ToString());
                            lblDifference.Text = Math.Round(double.Parse(drRow[1].ToString()), 0).ToString();

                            //Actual Available Cash
                            DataRow drActualCashAvailable = dsResult.Tables[0].NewRow();
                            drActualCashAvailable[1] = "ACTUAL CASH AVAILABLE";
                            drActualCashAvailable[3] = ActualCashAvailable;
                            dsResult.Tables[0].Rows.Add(drActualCashAvailable);

                            //Difference
                            DataRow drDifference = dsResult.Tables[0].NewRow();
                            drDifference[1] = "DIFFERENCE";
                            drDifference[3] = lblDifference.Text;
                            dsResult.Tables[0].Rows.Add(drDifference);
                        }
                        else
                        {
                            ActualCashAvailable = 0;
                            lblDifference.Text = string.Empty;
                        }
                        txtActualAmount.Enabled = true;
                        btnEditAvailableCash.Enabled = true;
                    }
                    else
                    {
                        ActualCashAvailable = 0;
                        txtActualAmount.Enabled = false;
                        btnEditAvailableCash.Enabled = false;
                    }

                    if (ActualCashAvailable != 0)
                    {
                        txtActualAmount.Text = ActualCashAvailable.ToString();
                        txtActualAmount.ReadOnly = true;
                        btnSaveActualCash.Enabled = false;
                        btnEditAvailableCash.Enabled = true;
                        //btnSaveActualCash.Enabled = true;
                    }
                    else
                    {
                        txtActualAmount.Clear();
                        txtActualAmount.ReadOnly = false;
                        btnSaveActualCash.Enabled = true;
                        btnEditAvailableCash.Enabled = false;
                        //btnSaveActualCash.Enabled = false;
                    }

                    DataTable dtIndSales = new DataTable();
                    dtIndSales.Columns.Add("ID", typeof(string));           //0
                    dtIndSales.Columns.Add("Cashier", typeof(string));      //1
                    dtIndSales.Columns.Add("Sales", typeof(string));        //2
                    dtIndSales.Columns.Add("Discounts", typeof(string));    //3

                    dtIndSales.Columns.Add("CakeAdvances", typeof(string)); //4
                    dtIndSales.Columns.Add("CakeDiscounts", typeof(string));//5
                    dtIndSales.Columns.Add("CakeBalances", typeof(string)); //6

                    dtIndSales.Columns.Add("BOAdvances", typeof(string));   //7 -
                    dtIndSales.Columns.Add("BOBalances", typeof(string));   //8 -

                    dtIndSales.Columns.Add("Expenses", typeof(string));     //9     4
                    dtIndSales.Columns.Add("Sodexho", typeof(string));      //10     5
                    dtIndSales.Columns.Add("CreditCard", typeof(string));   //11     6
                    dtIndSales.Columns.Add("Advance/Bills", typeof(string));//12    7
                    dtIndSales.Columns.Add("CashAvailable", typeof(string));//13    8
                    dtIndSales.Columns.Add("CashInHand", typeof(string));   //14    9
                    dtIndSales.Columns.Add("Difference", typeof(string));   //15    10

                    //Cashier Wise POS Sales and POS Discounts - 10
                    foreach (DataRow row in dsResult.Tables[10].Rows)
                    {
                        DataRow r = dtIndSales.NewRow();
                        r["ID"] = row[0];
                        r["Cashier"] = row[1];
                        r["Sales"] = row[2];
                        r["Discounts"] = row[3];
                        dtIndSales.Rows.Add(r);
                    }

                    //CakeAdvances, CakeDiscounts
                    foreach (DataRow mainRow in dsResult.Tables[13].Rows)
                    {
                        foreach (DataRow row in dtIndSales.Rows)
                        {
                            if (mainRow["Cashier"].ToString().Trim() == row["ID"].ToString().Trim())
                            {
                                row["CakeAdvances"] = mainRow["Advance"];
                                row["CakeDiscounts"] = mainRow["CakeDiscounts"];
                            }
                        }
                    }

                    //CakeBalances
                    foreach (DataRow mainRow in dsResult.Tables[14].Rows)
                    {
                        foreach (DataRow row in dtIndSales.Rows)
                        {
                            if (mainRow["Cashier"].ToString().Trim() == row["ID"].ToString().Trim())
                            {
                                row["CakeBalances"] = mainRow["CakeBalances"];
                            }
                        }
                    }

                    //Bulk Order Advances - 15
                    foreach (DataRow mainRow in dsResult.Tables[15].Rows)
                    {
                        foreach (DataRow row in dtIndSales.Rows)
                        {
                            if (mainRow["Cashier"].ToString().Trim() == row["ID"].ToString().Trim())
                            {
                                row["BOAdvances"] = mainRow["Advance"];
                            }
                        }
                    }

                    //Bulk Order Balances - 16
                    foreach (DataRow mainRow in dsResult.Tables[16].Rows)
                    {
                        foreach (DataRow row in dtIndSales.Rows)
                        {
                            if (mainRow["Cashier"].ToString().Trim() == row["ID"].ToString().Trim())
                            {
                                row["BOBalances"] = mainRow["Balance"];
                            }
                        }
                    }

                    //Cashier Wise Expenses - 11
                    foreach (DataRow mainRow in dsResult.Tables[11].Rows)
                    {
                        foreach (DataRow row in dtIndSales.Rows)
                        {
                            if (mainRow["Cashier"].ToString().Trim() == row["ID"].ToString().Trim())
                            {
                                row["Expenses"] = mainRow["ExpenseAmount"];
                            }
                        }
                    }

                    //Cashier Wise Sodexho & Credit Card Amounts - 12
                    foreach (DataRow mainRow in dsResult.Tables[12].Rows)
                    {
                        foreach (DataRow row in dtIndSales.Rows)
                        {
                            if (mainRow["Cashier"].ToString().Trim() == row["ID"].ToString().Trim())
                            {
                                row["Sodexho"] = mainRow["SodexhoAmount"];
                                row["CreditCard"] = mainRow["CreditCardAmount"];
                            }
                        }
                    }

                    //Employees Advances & Bills - dsAdvancesAndBills
                    if (dsAdvancesAndBills != null && dsAdvancesAndBills.Tables != null && dsAdvancesAndBills.Tables.Count > 1)
                    {
                        foreach (DataRow mainRow in dsAdvancesAndBills.Tables[1].Rows)
                        {
                            foreach (DataRow row in dtIndSales.Rows)
                            {
                                if (mainRow["Cashier"].ToString().Trim() == row["ID"].ToString().Trim())
                                {
                                    row["Advance/Bills"] = mainRow["EmployeeDebitAmount"];
                                }
                            }
                        }
                    }

                    //Calculating Total Available Amount
                    foreach (DataRow row in dtIndSales.Rows)
                    {
                        //POS Sales
                        double sales = 0d;
                        double.TryParse(row[2].ToString(), out sales);
                        if (sales == 0)
                        {
                            row[2] = string.Empty;
                        }

                        //POS Discounts
                        double discs = 0d;
                        double.TryParse(row[3].ToString(), out discs);
                        if (discs == 0)
                        {
                            row[3] = string.Empty;
                        }

                        //Cake Sales
                        double cakeAdvance = 0d;
                        double.TryParse(row[4].ToString(), out cakeAdvance);
                        if (cakeAdvance == 0)
                        {
                            row[4] = string.Empty;
                        }

                        double cakeDisc = 0d;
                        double.TryParse(row[5].ToString(), out cakeDisc);
                        if (cakeDisc == 0)
                        {
                            row[5] = string.Empty;
                        }

                        double cakeBal = 0d;
                        double.TryParse(row[6].ToString(), out cakeBal);
                        if (cakeBal == 0)
                        {
                            row[6] = string.Empty;
                        }

                        //Bulk Orders
                        double boAdv = 0d;
                        double.TryParse(row[7].ToString(), out boAdv);
                        if (boAdv == 0)
                        {
                            row[7] = string.Empty;
                        }

                        double boBal = 0d;
                        double.TryParse(row[8].ToString(), out boBal);
                        if (boBal == 0)
                        {
                            row[8] = string.Empty;
                        }

                        //+3

                        //Expenses
                        double expen = 0d;
                        double.TryParse(row[9].ToString(), out expen);
                        if (expen == 0)
                        {
                            row[9] = string.Empty;
                        }

                        //Sodexho
                        double sodexho = 0d;
                        double.TryParse(row[10].ToString(), out sodexho);
                        if (sodexho == 0)
                        {
                            row[10] = string.Empty;
                        }

                        //CreditCard
                        double credit = 0d;
                        double.TryParse(row[11].ToString(), out credit);
                        if (credit == 0)
                        {
                            row[11] = string.Empty;
                        }

                        //Advances & Bills
                        double advan = 0d;
                        double.TryParse(row[12].ToString(), out advan);
                        if (advan == 0)
                        {
                            row[12] = string.Empty;
                        }

                        row[13] = (sales - discs - expen - sodexho - credit - advan + cakeAdvance - cakeDisc + cakeBal + boAdv + boBal).ToString();
                    }

                    /*//Cake Sales
                    DataRow cakeRow = dtIndSales.NewRow();
                    cakeRow[0] = string.Empty;
                    cakeRow[1] = "Cake Sales";
                    cakeRow[2] = cakeSales.ToString();
                    cakeRow[3] = cakeDiscounts.ToString();
                    cakeRow[4] = string.Empty;
                    cakeRow[5] = string.Empty;
                    cakeRow[6] = string.Empty;
                    cakeRow[7] = string.Empty;
                    cakeRow[8] = (cakeSales - cakeDiscounts).ToString();
                    dtIndSales.Rows.Add(cakeRow);

                    //Bulk Orders
                    DataRow bulkRow = dtIndSales.NewRow();
                    bulkRow[0] = string.Empty;
                    bulkRow[1] = "Bulk Sales";
                    bulkRow[2] = bulkOrderAmt.ToString();
                    bulkRow[3] = string.Empty;
                    bulkRow[4] = string.Empty;
                    bulkRow[5] = string.Empty;
                    bulkRow[6] = string.Empty;
                    bulkRow[7] = string.Empty;
                    bulkRow[8] = bulkOrderAmt.ToString();
                    dtIndSales.Rows.Add(bulkRow);*/

                    //Get Actual Amounts If Entered
                    DataTable dsActuals = DBHelper.GetActuals(dpDate.Value, cmbBranch.SelectedValue.ToString(), dtIndSales);
                    if (dsActuals != null)
                    {
                        foreach (DataRow row in dtIndSales.Rows)
                        {
                            DataRow[] rows = dsActuals.Select("Type = '" + row["Cashier"].ToString() + "'");
                            if (rows != null && rows.Count() > 0)
                            {
                                row["CashInHand"] = rows[0][1].ToString();
                                row["Difference"] = rows[0][2].ToString();
                            }
                        }
                    }

                    dgvIndividualSales.DataSource = dtIndSales;

                    dgvIndividualSales.Columns[0].ReadOnly = true;
                    dgvIndividualSales.Columns[1].ReadOnly = true;
                    dgvIndividualSales.Columns[2].ReadOnly = true;
                    dgvIndividualSales.Columns[3].ReadOnly = true;
                    dgvIndividualSales.Columns[4].ReadOnly = true;
                    dgvIndividualSales.Columns[5].ReadOnly = true;
                    dgvIndividualSales.Columns[6].ReadOnly = true;
                    dgvIndividualSales.Columns[7].ReadOnly = true;
                    dgvIndividualSales.Columns[8].ReadOnly = true;
                    dgvIndividualSales.Columns[9].ReadOnly = true;
                    dgvIndividualSales.Columns[10].ReadOnly = true;
                    dgvIndividualSales.Columns[11].ReadOnly = true;
                    dgvIndividualSales.Columns[12].ReadOnly = true;
                    dgvIndividualSales.Columns[13].ReadOnly = true;
                    dgvIndividualSales.Columns[15].ReadOnly = true;

                    dgvIndividualSales.Columns[0].Width = 50;
                    dgvIndividualSales.Columns[1].Width = 120;
                    dgvIndividualSales.Columns[2].Width = 87;
                    dgvIndividualSales.Columns[3].Width = 87;
                    dgvIndividualSales.Columns[4].Width = 87;
                    dgvIndividualSales.Columns[5].Width = 87;
                    dgvIndividualSales.Columns[6].Width = 87;
                    dgvIndividualSales.Columns[7].Width = 87;
                    dgvIndividualSales.Columns[8].Width = 87;
                    dgvIndividualSales.Columns[9].Width = 87;
                    dgvIndividualSales.Columns[10].Width = 87;
                    dgvIndividualSales.Columns[11].Width = 87;
                    dgvIndividualSales.Columns[12].Width = 87;
                    dgvIndividualSales.Columns[13].Width = 87;
                    dgvIndividualSales.Columns[14].Width = 87;
                    dgvIndividualSales.Columns[15].Width = 87;

                    dgvIndividualSales.Columns[0].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[1].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[2].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[3].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[4].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[5].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[6].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[7].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[8].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[9].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[10].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[11].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[12].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[13].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[14].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);
                    dgvIndividualSales.Columns[15].HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Pixel);

                    dgvIndividualSales.Focus();
                }
                else
                {
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgvIndividualSales_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                string value = dgvIndividualSales[e.ColumnIndex, e.RowIndex].Value.ToString();

                double result = 0;
                double.TryParse(value, out result);
                if (result <= 0)
                {
                    dgvIndividualSales[e.ColumnIndex, e.RowIndex].Value = 0;
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgvIndividualSales_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = false;
        }

        private void dgvIndividualSales_KeyPress(object sender, KeyPressEventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                if (dgvIndividualSales.SelectedRows.Count > 0)
                {
                    dgvIndividualSales.SelectedRows[0].Cells[8].Selected = true;
                    if (e.KeyChar > 47 && e.KeyChar < 58)
                    {
                        dgvIndividualSales.SelectedRows[0].Cells[8].Value = double.Parse(((char)e.KeyChar).ToString());
                        dgvIndividualSales.BeginEdit(false);
                    }
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //Save the Available Cash
        private void btnSaveDtls_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                bool isEntered = false;

                foreach (DataGridViewRow row in dgvIndividualSales.Rows)
                {
                    if (row.Cells["CashInHand"].Value.ToString() != string.Empty && row.Cells["CashInHand"].Value.ToString() != "0")
                    {
                        isEntered = true;
                        break;
                    }
                }

                if (isEntered)
                {
                    if (DBHelper.SaveActuals(SelectedDate, cmbBranch.SelectedValue.ToString(), dgvIndividualSales) > 0)
                    {
                        MessageBox.Show("Available Cash Saved Successfully", "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        //txtActualAmount.ReadOnly = true;
                        //btnSaveActualCash.Enabled = false;
                        //btnEditAvailableCash.Enabled = true;
                        btnFetch_Click(sender, e);
                    }
                    else
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Some unknown error has occurred.", "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show("Enter Valid Values", "Invalid Values", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnPrintFinancialReport_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgFinancialReport.DataSource != null)
                {
                    PrintDGV.Branch = Branch;
                    PrintDGV.Date = Date;
                    PrintDGV.ReportType = "Financial Report";
                    PrintDGV.Print_DataGridView(dgFinancialReport);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSaveActualCash_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtActualAmount.Text.Trim() != string.Empty)
                {
                    if (DBHelper.SaveAvailableCash(SelectedDate, cmbBranch.SelectedValue.ToString(), ApplicationCashAvailable, ActualCashAvailable, (ActualCashAvailable - ApplicationCashAvailable)) > 0)
                    {
                        MessageBox.Show("Available Cash Saved Successfully", "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        txtActualAmount.ReadOnly = true;
                        btnSaveActualCash.Enabled = false;
                        btnEditAvailableCash.Enabled = true;
                        btnFetch_Click(sender, e);
                    }
                    else
                    {
                        MessageBox.Show("Some unknown error has occurred.", "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnEditAvailableCash_Click(object sender, EventArgs e)
        {
            btnEditAvailableCash.Enabled = false;
            btnSaveActualCash.Enabled = true;
            txtActualAmount.ReadOnly = false;
        }

        private void txtActualAmount_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (!txtActualAmount.ReadOnly)
                {
                    double temp;
                    if (!(double.TryParse(txtActualAmount.Text, out temp)))
                    {
                        txtActualAmount.Clear();
                        lblDifference.Text = string.Empty;
                    }
                    else
                    {
                        ActualCashAvailable = temp;
                        lblDifference.Text = (Math.Round(ActualCashAvailable - ApplicationCashAvailable, 0)).ToString();
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dpDate_ValueChanged(object sender, EventArgs e)
        {
            //if (tabMainCtrl.SelectedIndex == 2)
            //    chkBranchConnect.Checked = ((sender as DateTimePicker).Value.ToString("dd/MM/yyyy") == DateTime.Now.ToString("dd/MM/yyyy"));
        }

        #endregion

        #region Monthly Report

        private void btnMonthlyReport_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    DataTable dtBrnchs = DBHelper.GetBranches();
                    DataRow row = dtBrnchs.NewRow();
                    row[1] = "All";
                    row[0] = 0;
                    dtBrnchs.Rows.Add(row);
                    cmbBranchesMonth.DataSource = dtBrnchs;
                    cmbBranchesMonth.DisplayMember = "BranchName";
                    cmbBranchesMonth.ValueMember = "BranchID";
                    tabMainCtrl.SelectTab(3);

                    cmbBranchesMonth.SelectedIndex = BranchIndex;
                    dpDateMonthly.Value = SelectedDate;

                    //cmbBranchesMonth.SelectedIndex = 0;
                    //dpDateMonthly.Value = DateTime.Now;
                    dgMonthlyReport.DataSource = null;

                    lblPOSSalesMontly.Text = "POS Sales: ";
                    lblCakeSalesMonthly.Text = "Cake Sales: ";
                    lblDiscountMontly.Text = "Discount: ";
                    lblTotalSalesMontly.Text = "Total Sales: ";
                    lblExpensesMonthly.Text = "Expenses: ";
                    lblSodexhoSalesMonthly.Text = "Sodexho Sales: ";
                    lblCardSalesMontly.Text = "Card Sales: ";
                    label6.Text = "Emp Advance/Bill Amounts: ";
                    label4.Text = "Credit Note Amount: ";
                    label12.Text = "Cash Available: ";
                    lblBulkOrdersMontly.Text = "Bulk Orders: ";
                }
                catch (Exception)
                {
                    MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabMainCtrl.SelectTab(22);
                txtUserName.Focus();
            }
        }

        private void btnFetchMontlyReport_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                Branch = cmbBranchesMonth.Text;
                Date = dpDateMonthly.Value;

                if (cmbBranchesMonth.SelectedIndex < 5)
                    BranchIndex = cmbBranchesMonth.SelectedIndex;
                SelectedDate = dpDateMonthly.Value;

                DataSet dsResult = DBHelper.GetMonthlyReport(dpDateMonthly.Value, cmbBranchesMonth.SelectedValue.ToString());

                double cakeSales = 0d;
                double discounts = 0d;
                double totalSales = 0d;
                double expenseAmt = 0d;
                double sodexhoAmt = 0d;
                double creditCardAmt = 0d;
                double salariesAmt = 0d;
                double creditNoteAmount = 0d;
                double bulkOrdersAmt = 0d;

                if (dsResult != null)
                {
                    //Empty Row
                    dsResult.Tables[0].Rows.Add(dsResult.Tables[0].NewRow());

                    //POS Sales
                    DataRow drSales = dsResult.Tables[0].NewRow();
                    drSales[1] = "POS SALES";
                    drSales[3] = dsResult.Tables[1].Rows[0]["POSSales"].ToString();
                    dsResult.Tables[0].Rows.Add(drSales);

                    //Cake Sales
                    double tmpValue = 0d;

                    if (double.TryParse(dsResult.Tables[2].Rows[0]["Advance"].ToString(), out tmpValue))
                        cakeSales += tmpValue;
                    if (double.TryParse(dsResult.Tables[3].Rows[0]["Balance"].ToString(), out tmpValue))
                        cakeSales += tmpValue;

                    DataRow drCakeSales = dsResult.Tables[0].NewRow();
                    drCakeSales[1] = "CAKE SALES";
                    drCakeSales[3] = cakeSales.ToString();
                    dsResult.Tables[0].Rows.Add(drCakeSales);

                    //Discount
                    tmpValue = 0d;

                    if (dsResult.Tables[1].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[1].Rows[0]["POSDiscounts"].ToString(), out tmpValue))
                            discounts += tmpValue;
                    }

                    if (dsResult.Tables[2].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[2].Rows[0]["CakeDiscounts"].ToString(), out tmpValue))
                            discounts += tmpValue;
                    }

                    DataRow drDiscount = dsResult.Tables[0].NewRow();
                    drDiscount[1] = "DISCOUNT";
                    drDiscount[3] = Math.Round(discounts, 2);
                    dsResult.Tables[0].Rows.Add(drDiscount);

                    //Vendor Sales
                    double vendorSales = 0d;

                    double.TryParse(dsResult.Tables[7].Rows[0]["VendorSales"].ToString(), out vendorSales);
                    DataRow drVendorSales = dsResult.Tables[0].NewRow();
                    drVendorSales[1] = "VENDOR SALES";
                    drVendorSales[3] = vendorSales.ToString();
                    dsResult.Tables[0].Rows.Add(drVendorSales);

                    if (dsResult.Tables[8] != null && dsResult.Tables[8].Rows.Count > 0)
                    {
                        double.TryParse(dsResult.Tables[8].Rows[0]["BulkOrderAdvance"].ToString(), out tmpValue);
                        bulkOrdersAmt += tmpValue;
                    }

                    if (dsResult.Tables[9] != null && dsResult.Tables[9].Rows.Count > 0)
                    {
                        double.TryParse(dsResult.Tables[9].Rows[0]["BulkOrderBalance"].ToString(), out tmpValue);
                        bulkOrdersAmt += tmpValue;
                    }

                    DataRow drBulkOrder = dsResult.Tables[0].NewRow();
                    drBulkOrder[1] = "BULK ORDERS";
                    drBulkOrder[3] = bulkOrdersAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drBulkOrder);

                    //Total Sales
                    tmpValue = 0d;

                    if (dsResult.Tables[1].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[1].Rows[0]["POSSales"].ToString(), out tmpValue))
                            totalSales += tmpValue;
                    }
                    totalSales += cakeSales;
                    totalSales += bulkOrdersAmt;

                    DataRow drTotalSales = dsResult.Tables[0].NewRow();
                    drTotalSales[1] = "TOTAL SALES";
                    drTotalSales[3] = (totalSales - discounts + creditNoteAmount).ToString();
                    dsResult.Tables[0].Rows.Add(drTotalSales);

                    //Expense Amounts
                    tmpValue = 0d;

                    if (dsResult.Tables[4].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[4].Rows[0]["ExpenseAmount"].ToString(), out tmpValue))
                            expenseAmt = tmpValue;
                    }

                    DataRow drExpense = dsResult.Tables[0].NewRow();
                    drExpense[1] = "EXPENSE AMOUNT";
                    drExpense[3] = expenseAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drExpense);

                    //Sodexho Amount
                    tmpValue = 0d;

                    if (dsResult.Tables[5].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[5].Rows[0]["SodexhoAmount"].ToString(), out tmpValue))
                            sodexhoAmt = tmpValue;
                    }

                    DataRow drSodexho = dsResult.Tables[0].NewRow();
                    drSodexho[1] = "SODEXHO AMOUNT";
                    drSodexho[3] = sodexhoAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drSodexho);

                    //CreditCard Amount
                    tmpValue = 0d;

                    if (dsResult.Tables[5].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[5].Rows[0]["CreditCardAmount"].ToString(), out tmpValue))
                            creditCardAmt = tmpValue;
                    }

                    DataRow drCard = dsResult.Tables[0].NewRow();
                    drCard[1] = "CREDITCARD AMOUNT";
                    drCard[3] = creditCardAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drCard);

                    //Get Advances & Bill from Salaries Application
                    salariesAmt = DBHelper.GetEmpAdvancesandBillsForMonth(dpDateMonthly.Value, cmbBranchesMonth.SelectedValue.ToString());

                    DataRow drSalariesApp = dsResult.Tables[0].NewRow();
                    drSalariesApp[1] = "EMP ADVANCES/BILLS";
                    drSalariesApp[3] = salariesAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drSalariesApp);

                    if (dsResult.Tables[6].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[6].Rows[0]["CreditNoteAmount"].ToString(), out tmpValue))
                            creditNoteAmount = tmpValue;
                    }

                    //Credit Note Amount
                    DataRow drCreditNoteAmount = dsResult.Tables[0].NewRow();
                    drCreditNoteAmount[1] = "CREDIT NOTES AMOUNT";
                    drCreditNoteAmount[3] = creditNoteAmount;
                    dsResult.Tables[0].Rows.Add(drCreditNoteAmount);

                    //Available Cash
                    DataRow drAvailableCash = dsResult.Tables[0].NewRow();
                    drAvailableCash[1] = "AVAILABLE CASH";
                    drAvailableCash[3] = Math.Round(totalSales - discounts - expenseAmt - sodexhoAmt - creditCardAmt - salariesAmt, 2);
                    dsResult.Tables[0].Rows.Add(drAvailableCash);

                    dgMonthlyReport.DataSource = dsResult.Tables[0];
                    dgMonthlyReport.Columns[0].Width = 80;
                    dgMonthlyReport.Columns[1].Width = 170;
                    dgMonthlyReport.Columns[2].Width = 70;
                    dgMonthlyReport.Columns[3].Width = 100;

                    lblPOSSalesMontly.Text = "POS Sales: " + dsResult.Tables[1].Rows[0]["POSSales"].ToString();
                    lblCakeSalesMonthly.Text = "Cake Sales: " + cakeSales.ToString();
                    lblDiscountMontly.Text = "Discount: " + discounts.ToString();
                    lblTotalSalesMontly.Text = "Total Sales: " + (totalSales - discounts + creditNoteAmount).ToString();
                    lblExpensesMonthly.Text = "Expenses: " + expenseAmt.ToString();
                    lblSodexhoSalesMonthly.Text = "Sodexho Sales: " + sodexhoAmt.ToString();
                    lblCardSalesMontly.Text = "Card Sales: " + creditCardAmt.ToString();
                    label6.Text = "Emp Advance/Bill Amounts: " + salariesAmt.ToString();
                    label4.Text = "Credit Note Amount: " + creditNoteAmount.ToString();
                    label12.Text = "Cash Available: " + Math.Round((totalSales - discounts - expenseAmt - sodexhoAmt - creditCardAmt - salariesAmt), 2).ToString();
                    lblBulkOrdersMontly.Text = "Bulk Orders: " + Math.Round(bulkOrdersAmt, 2).ToString();
                }
                else
                {
                    dgMonthlyReport.DataSource = null;
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnMonthlyReportPrint_Click(object sender, EventArgs e)
        {
            if (dgMonthlyReport.DataSource != null)
            {
                PrintDGV.Branch = Branch;
                PrintDGV.Date = Date;
                PrintDGV.ReportType = "Monthly Report";
                PrintDGV.Print_DataGridView(dgMonthlyReport);
            }
        }

        private void dpDateMonthly_ValueChanged(object sender, EventArgs e)
        {
            //if (tabMainCtrl.SelectedIndex == 3)
            //    chkBranchConnect.Checked = ((sender as DateTimePicker).Value.ToString("dd/MM/yyyy") == DateTime.Now.ToString("dd/MM/yyyy"));
        }

        #endregion

        #region Remaining Stock

        private void btnRemainingStock_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    if (dtBranches == null)
                        dtBranches = DBHelper.GetBranches();
                    cmbBranchRemainingStock.DataSource = dtBranches;
                    cmbBranchRemainingStock.DisplayMember = "BranchName";
                    cmbBranchRemainingStock.ValueMember = "BranchID";
                    tabMainCtrl.SelectTab(4);

                    cmbBranchRemainingStock.SelectedIndex = BranchIndex;
                    dpRemainingStock.Value = SelectedDate;

                    dgRemainingStock.DataSource = null;
                }
                catch (Exception)
                {
                    MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabMainCtrl.SelectTab(22);
                txtUserName.Focus();
            }
        }

        private void btnFetchRemainingStock_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                dgRemainingStock.DataSource = DBHelper.GetStockByBranch(cmbBranchRemainingStock.SelectedValue.ToString(), dpRemainingStock.Value);
                Date = DateTime.Now;
                Branch = cmbBranchRemainingStock.Text;
                BranchIndex = cmbBranchRemainingStock.SelectedIndex;

                if (dgRemainingStock.DataSource != null)
                {
                    dgRemainingStock.Columns[0].Width = 70;
                    dgRemainingStock.Columns[1].Width = 230;
                    dgRemainingStock.Columns[2].Width = 105;
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnPrintRemainingStock_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgRemainingStock.DataSource != null)
                {
                    PrintDGV.Branch = Branch;
                    PrintDGV.Date = Date;
                    PrintDGV.ReportType = "Remaining Items Report";
                    PrintDGV.Print_DataGridView(dgRemainingStock);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dpRemainingStock_ValueChanged(object sender, EventArgs e)
        {
            if (tabMainCtrl.SelectedIndex == 4)
                chkBranchConnect.Checked = ((sender as DateTimePicker).Value.ToString("dd/MM/yyyy") == DateTime.Now.ToString("dd/MM/yyyy"));
        }

        #endregion

        #region Expenses

        private void btnExpenses_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    if (dtBranches == null)
                        dtBranches = DBHelper.GetBranches();
                    cmbBranchExpenses.DataSource = dtBranches;
                    cmbBranchExpenses.DisplayMember = "BranchName";
                    cmbBranchExpenses.ValueMember = "BranchID";
                    tabMainCtrl.SelectTab(5);

                    dtExpensesDate.Value = SelectedDate;
                    chkCompleteMonth.Checked = IsCheckedMontly;
                    cmbBranchExpenses.SelectedIndex = BranchIndex;
                    dgExpenses.DataSource = null;
                }
                catch (Exception)
                {
                    MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabMainCtrl.SelectTab(22);
                txtUserName.Focus();
            }
        }

        private void btnFetchExpenses_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                SelectedDate = dtExpensesDate.Value;
                BranchIndex = cmbBranchExpenses.SelectedIndex;
                IsCheckedMontly = chkCompleteMonth.Checked;
                bool IsException = false;

                DataSet ds = DBHelper.GetExpenseByBranchAndDate(cmbBranchExpenses.SelectedValue.ToString(), dtExpensesDate.Value, chkCompleteMonth.Checked, out IsException);

                if (IsException)
                {
                    dgExpenses.DataSource = null;
                    MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (ds != null && ds.Tables.Count == 2)
                {
                    DataRow drTotalExpenses = ds.Tables[0].NewRow();
                    drTotalExpenses[1] = "TOTAL";
                    drTotalExpenses[3] = ds.Tables[1].Rows[0][0].ToString();
                    ds.Tables[0].Rows.Add(drTotalExpenses);

                    dgExpenses.DataSource = ds.Tables[0];

                    Date = dtExpensesDate.Value;
                    Branch = cmbBranchExpenses.Text;
                    IsMonthly = chkCompleteMonth.Checked;

                    if (dgExpenses.DataSource != null)
                    {
                        dgExpenses.Columns[0].Width = 70;
                        dgExpenses.Columns[1].Width = 150;
                        dgExpenses.Columns[2].Width = 200;
                        dgExpenses.Columns[3].Width = 100;
                    }
                }
                else
                {
                    dgExpenses.DataSource = null;
                    MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnExpensesPrint_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgExpenses.DataSource != null)
                {
                    PrintDGV.Branch = Branch;
                    PrintDGV.Date = Date;
                    PrintDGV.IsMonthly = IsMonthly;
                    PrintDGV.ReportType = "Expenses Report";
                    PrintDGV.Print_DataGridView(dgExpenses);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dtExpensesDate_ValueChanged(object sender, EventArgs e)
        {
            if (tabMainCtrl.SelectedIndex == 5)
                chkBranchConnect.Checked = ((sender as DateTimePicker).Value.ToString("dd/MM/yyyy") == DateTime.Now.ToString("dd/MM/yyyy"));
        }

        #endregion

        #region Credit Notes

        private void btnCreditNotes_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    if (dtBranches == null)
                        dtBranches = DBHelper.GetBranches();
                    cmbBranchCreditNote.DataSource = dtBranches;
                    cmbBranchCreditNote.DisplayMember = "BranchName";
                    cmbBranchCreditNote.ValueMember = "BranchID";
                    cmbCompany.DataSource = DBHelper.GetAllCompaniesByBranch("0");
                    if (cmbCompany.DataSource != null)
                    {
                        cmbCompany.DisplayMember = "CreditNoteCompany";
                        cmbCompany.ValueMember = "ID";
                    }
                    tabMainCtrl.SelectTab(6);

                    dpDateCreditNotes.Value = SelectedDate;
                    chkCompleteMonthCreditNote.Checked = IsCheckedMontly;
                    cmbBranchCreditNote.SelectedIndex = BranchIndex;
                    dgCreditNotes.DataSource = null;
                }
                catch (Exception)
                {
                    MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabMainCtrl.SelectTab(22);
                txtUserName.Focus();
            }
        }

        private void btnGetCreditNotes_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                SelectedDate = dpDateCreditNotes.Value;
                BranchIndex = cmbBranchCreditNote.SelectedIndex;
                IsCheckedMontly = chkCompleteMonthCreditNote.Checked;
                bool IsException = false;

                DataSet ds = DBHelper.GetCreditNotes(cmbBranchCreditNote.SelectedValue.ToString(), dpDateCreditNotes.Value, chkCompleteMonthCreditNote.Checked, cmbCompany.SelectedValue.ToString(), out IsException);

                if (IsException)
                {
                    dgCreditNotes.DataSource = null;
                    MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (ds != null && ds.Tables.Count == 2)
                {
                    DataRow drTotal = ds.Tables[0].NewRow();
                    drTotal[0] = "TOTAL";
                    drTotal[2] = ds.Tables[1].Rows[0][0].ToString();
                    ds.Tables[0].Rows.Add(drTotal);

                    dgCreditNotes.DataSource = ds.Tables[0];

                    Date = dpDateCreditNotes.Value;
                    Branch = cmbBranchCreditNote.Text;
                    IsMonthly = chkCompleteMonthCreditNote.Checked;

                    if (dgCreditNotes.DataSource != null)
                    {
                        dgCreditNotes.Columns[0].Width = 250;
                        dgCreditNotes.Columns[1].Width = 100;
                        dgCreditNotes.Columns[2].Width = 100;
                    }
                }
                else
                {
                    dgCreditNotes.DataSource = null;
                    MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnPrintCreditNote_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgCreditNotes.DataSource != null)
                {
                    PrintDGV.Branch = Branch;
                    PrintDGV.Date = Date;
                    PrintDGV.IsMonthly = IsMonthly;
                    PrintDGV.ReportType = "Credit Notes Report";
                    PrintDGV.Print_DataGridView(dgCreditNotes);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void cmbBranchCreditNote_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cmbBranchCreditNote.SelectedIndex > 0)
                {
                    cmbCompany.DataSource = DBHelper.GetAllCompaniesByBranch(cmbBranchCreditNote.SelectedValue.ToString());
                    if (cmbCompany.DataSource != null)
                    {
                        cmbCompany.DisplayMember = "CreditNoteCompany";
                        cmbCompany.ValueMember = "ID";
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dpDateCreditNotes_ValueChanged(object sender, EventArgs e)
        {
            if (tabMainCtrl.SelectedIndex == 6)
                chkBranchConnect.Checked = ((sender as DateTimePicker).Value.ToString("dd/MM/yyyy") == DateTime.Now.ToString("dd/MM/yyyy"));
        }

        #endregion

        #region Damages

        private void btnDamages_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    if (dtBranches == null)
                        dtBranches = DBHelper.GetBranches();
                    cmbBranchDamages.DataSource = dtBranches;
                    cmbBranchDamages.DisplayMember = "BranchName";
                    cmbBranchDamages.ValueMember = "BranchID";
                    tabMainCtrl.SelectTab(7);

                    dpDateDamages.Value = SelectedDate;
                    chkMonthDamages.Checked = IsCheckedMontly;
                    cmbBranchDamages.SelectedIndex = BranchIndex;
                    dgDamages.DataSource = null;
                }
                catch (Exception)
                {
                    MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabMainCtrl.SelectTab(22);
                txtUserName.Focus();
            }
        }

        private void btnFetchDamages_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;

            try
            {
                SelectedDate = dpDateDamages.Value;
                BranchIndex = cmbBranchDamages.SelectedIndex;
                IsCheckedMontly = chkMonthDamages.Checked;
                bool IsException = false;

                DataSet dsDetails = DBHelper.GetDamages(cmbBranchDamages.SelectedValue.ToString(), dpDateDamages.Value, chkMonthDamages.Checked, out IsException);

                if (IsException)
                {
                    dgDamages.DataSource = null;
                    MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (dsDetails != null && dsDetails.Tables.Count == 2)
                {
                    DataRow drTotalDamages = dsDetails.Tables[0].NewRow();
                    drTotalDamages[1] = "TOTAL";
                    drTotalDamages[3] = dsDetails.Tables[1].Rows[0][0].ToString();
                    dsDetails.Tables[0].Rows.Add(drTotalDamages);

                    dgExpenses.DataSource = dsDetails.Tables[0];

                    dgDamages.DataSource = dsDetails.Tables[0];
                    Date = dpDateDamages.Value;
                    Branch = cmbBranchDamages.Text;
                    IsMonthly = chkMonthDamages.Checked;

                    dgDamages.Columns[0].Width = 70;
                    dgDamages.Columns[1].Width = 200;
                    dgDamages.Columns[2].Width = 100;
                }
                else
                {
                    dgDamages.DataSource = null;
                    MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnPrintDamages_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgDamages.DataSource != null)
                {
                    PrintDGV.Branch = Branch;
                    PrintDGV.Date = Date;
                    PrintDGV.IsMonthly = IsMonthly;
                    PrintDGV.ReportType = "Damages Report";
                    PrintDGV.Print_DataGridView(dgDamages);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dpDateDamages_ValueChanged(object sender, EventArgs e)
        {
            if (tabMainCtrl.SelectedIndex == 7)
                chkBranchConnect.Checked = ((sender as DateTimePicker).Value.ToString("dd/MM/yyyy") == DateTime.Now.ToString("dd/MM/yyyy"));
        }

        #endregion

        #region Cancelled Bills

        private void btnCancelledBills_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    if (dtBranches == null)
                        dtBranches = DBHelper.GetBranches();
                    cmbBranchCancelledBills.DataSource = dtBranches;
                    cmbBranchCancelledBills.DisplayMember = "BranchName";
                    cmbBranchCancelledBills.ValueMember = "BranchID";
                    tabMainCtrl.SelectTab(8);

                    dtpCancelledBills.Value = SelectedDate;
                    chkCancelledBills.Checked = IsCheckedMontly;
                    cmbBranchCancelledBills.SelectedIndex = BranchIndex;
                    dgCancelledBills.DataSource = null;
                    dgCancelledBillDetails.DataSource = null;
                }
                catch (Exception)
                {
                    MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabMainCtrl.SelectTab(22);
                txtUserName.Focus();
            }
        }

        private void btnGetCancelledBills_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                BranchIndex = cmbBranchCancelledBills.SelectedIndex;
                SelectedDate = dtpCancelledBills.Value;
                IsCheckedMontly = chkCancelledBills.Checked;
                bool IsException = false;
                tempBranch = cmbBranchCancelledBills.SelectedValue.ToString();

                dgCancelledBills.DataSource = DBHelper.GetCancelledBills(cmbBranchCancelledBills.SelectedValue.ToString(), dtpCancelledBills.Value, chkCancelledBills.Checked, out IsException);

                if (IsException)
                {
                    dgCancelledBills.DataSource = null;
                    dgCancelledBillDetails.DataSource = null;
                    MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (dgCancelledBills.DataSource != null)
                {
                    dgCancelledBills.Columns[0].Width = 80;
                    dgCancelledBills.Columns[1].Width = 50;
                    dgCancelledBills.Columns[2].Width = 50;
                    dgCancelledBills.Columns[3].Width = 90;
                    dgCancelledBills.Columns[4].Width = 90;
                    dgCancelledBills.Columns[5].Width = 140;
                    dgCancelledBills.Columns[6].Width = 150;
                    dgCancelledBills.Columns[7].Width = 200;
                    dgCancelledBills.Columns[8].Visible = false;
                    tempBranch = cmbBranchCancelledBills.SelectedValue.ToString();
                }
                else
                {
                    dgCancelledBills.DataSource = null;
                    dgCancelledBillDetails.DataSource = null;
                    MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgCancelledBills_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgCancelledBills.SelectedRows.Count > 0)
                {
                    string billNo = dgCancelledBills.SelectedRows[0].Cells[0].Value.ToString();

                    if (billNo != string.Empty)
                    {
                        bool IsException = false;
                        dgCancelledBillDetails.DataSource = DBHelper.GetBillDetailsByBillNo(billNo, tempBranch, DateTime.Parse(dgCancelledBills.SelectedRows[0].Cells[8].Value.ToString()), out IsException);

                        if (IsException)
                        {
                            dgCancelledBillDetails.DataSource = null;
                            MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        if (dgCancelledBillDetails.DataSource != null)
                        {
                            dgCancelledBillDetails.Columns[0].Width = 80;
                            dgCancelledBillDetails.Columns[1].Width = 80;
                            dgCancelledBillDetails.Columns[2].Width = 180;
                            dgCancelledBillDetails.Columns[3].Width = 80;
                        }
                        else
                        {
                            dgCancelledBillDetails.DataSource = null;
                            //MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dtpCancelledBills_ValueChanged(object sender, EventArgs e)
        {
            if (tabMainCtrl.SelectedIndex == 8)
                chkBranchConnect.Checked = ((sender as DateTimePicker).Value.ToString("dd/MM/yyyy") == DateTime.Now.ToString("dd/MM/yyyy"));
        }

        private void btnPrintCancelledBills_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgCancelledBills.DataSource != null && dgCancelledBills.Rows.Count > 0)
                {
                    PrintDGV.Branch = cmbBranchCancelledBills.Text;
                    PrintDGV.Date = dtpCancelledBills.Value;
                    PrintDGV.IsMonthly = chkCancelledBills.Checked;
                    PrintDGV.ReportType = "Cancelled Bills Report";
                    PrintDGV.Print_DataGridView(dgCancelledBills);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Discounted Bills

        private void btnDisc_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    if (dtBranches == null)
                        dtBranches = DBHelper.GetBranches();
                    cmbDiscountBranch.DataSource = dtBranches;
                    cmbDiscountBranch.DisplayMember = "BranchName";
                    cmbDiscountBranch.ValueMember = "BranchID";
                    tabMainCtrl.SelectTab(9);

                    dtDiscount.Value = SelectedDate;
                    chkDiscountMonth.Checked = IsCheckedMontly;
                    cmbDiscountBranch.SelectedIndex = BranchIndex;
                    dgDiscountedBills.DataSource = null;
                    dgDiscountedBillDetails.DataSource = null;
                }
                catch (Exception)
                {
                    MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabMainCtrl.SelectTab(22);
                txtUserName.Focus();
            }
        }

        private void btnDiscountedBills_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                SelectedDate = dtDiscount.Value;
                BranchIndex = cmbDiscountBranch.SelectedIndex;
                IsCheckedMontly = chkDiscountMonth.Checked;
                bool IsException = false;
                tempBranch = cmbDiscountBranch.SelectedValue.ToString();

                dgDiscountedBills.DataSource = DBHelper.GetDiscountedBills(cmbDiscountBranch.SelectedValue.ToString(), dtDiscount.Value, chkDiscountMonth.Checked, out IsException);

                if (IsException)
                {
                    dgDiscountedBills.DataSource = null;
                    MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (dgDiscountedBills.DataSource != null)
                {
                    dgDiscountedBills.Columns[0].Width = 80;
                    dgDiscountedBills.Columns[1].Width = 50;
                    dgDiscountedBills.Columns[2].Width = 50;
                    dgDiscountedBills.Columns[3].Width = 90;
                    dgDiscountedBills.Columns[4].Width = 90;
                    dgDiscountedBills.Columns[5].Width = 140;
                    dgDiscountedBills.Columns[6].Width = 150;
                    dgDiscountedBills.Columns[7].Width = 200;
                    dgDiscountedBills.Columns[8].Visible = false;
                    tempBranch = cmbDiscountBranch.SelectedValue.ToString();
                }
                else
                {
                    dgDiscountedBills.DataSource = null;
                    MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgDiscountedBills_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgDiscountedBills.SelectedRows.Count > 0)
                {
                    string billNo = dgDiscountedBills.SelectedRows[0].Cells[0].Value.ToString();

                    if (billNo != string.Empty)
                    {
                        bool IsException = false;

                        dgDiscountedBillDetails.DataSource = DBHelper.GetBillDetailsByBillNo(billNo, tempBranch, DateTime.Parse(dgDiscountedBills.SelectedRows[0].Cells[8].Value.ToString()), out IsException);

                        if (IsException)
                        {
                            dgDiscountedBillDetails.DataSource = null;
                            MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        if (dgDiscountedBillDetails.DataSource != null)
                        {
                            dgDiscountedBillDetails.Columns[0].Width = 80;
                            dgDiscountedBillDetails.Columns[1].Width = 80;
                            dgDiscountedBillDetails.Columns[2].Width = 180;
                            dgDiscountedBillDetails.Columns[3].Width = 80;
                        }
                        else
                        {
                            dgDiscountedBillDetails.DataSource = null;
                            MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dtDiscount_ValueChanged(object sender, EventArgs e)
        {
            if (tabMainCtrl.SelectedIndex == 9)
                chkBranchConnect.Checked = ((sender as DateTimePicker).Value.ToString("dd/MM/yyyy") == DateTime.Now.ToString("dd/MM/yyyy"));
        }

        private void btnDiscountedBillsPrint_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgDiscountedBills.DataSource != null && dgDiscountedBills.Rows.Count > 0)
                {
                    PrintDGV.Branch = cmbDiscountBranch.Text;
                    PrintDGV.Date = dtDiscount.Value;
                    PrintDGV.IsMonthly = chkDiscountMonth.Checked;
                    PrintDGV.ReportType = "Discounted Bills Report";
                    PrintDGV.Print_DataGridView(dgDiscountedBills);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Bulk Orders

        private void btnBulk_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    if (dtBranches == null)
                        dtBranches = DBHelper.GetBranches();
                    cmbBranchBulk.DataSource = dtBranches;
                    cmbBranchBulk.DisplayMember = "BranchName";
                    cmbBranchBulk.ValueMember = "BranchID";
                    tabMainCtrl.SelectTab(10);

                    dpDateBulk.Value = SelectedDate;
                    chkMonthBulk.Checked = IsCheckedMontly;
                    cmbBranchBulk.SelectedIndex = BranchIndex;
                    dgMainBulk.DataSource = null;
                    dgSubBulk.DataSource = null;
                }
                catch (Exception)
                {
                    MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabMainCtrl.SelectTab(22);
                txtUserName.Focus();
            }
        }

        private void btnBulkOrders_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                SelectedDate = dpDateBulk.Value;
                BranchIndex = cmbBranchBulk.SelectedIndex;
                IsCheckedMontly = chkMonthBulk.Checked;

                tempBranch = cmbBranchBulk.SelectedValue.ToString();

                bool IsException = false;

                dgMainBulk.DataSource = DBHelper.GetBulkOrders(cmbBranchBulk.SelectedValue.ToString(), dpDateBulk.Value, chkMonthBulk.Checked, out IsException);

                if (IsException)
                {
                    dgMainBulk.DataSource = null;
                    MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (dgMainBulk.DataSource != null)
                {

                }
                else
                {
                    dgMainBulk.DataSource = null;
                    MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgMainBulk_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgMainBulk.SelectedRows.Count > 0)
                {
                    string billNo = dgMainBulk.SelectedRows[0].Cells[0].Value.ToString();

                    if (billNo != string.Empty)
                    {
                        bool IsException = false;

                        dgSubBulk.DataSource = DBHelper.GetBillDetailsByBillNo(billNo, tempBranch, dpDateBulk.Value, out IsException);

                        if (IsException)
                        {
                            dgSubBulk.DataSource = null;
                            MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        if (dgSubBulk.DataSource != null)
                        {
                            dgSubBulk.Columns[0].Width = 80;
                            dgSubBulk.Columns[1].Width = 80;
                            dgSubBulk.Columns[2].Width = 180;
                            dgSubBulk.Columns[3].Width = 80;
                        }
                        else
                        {
                            dgSubBulk.DataSource = null;
                            MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dpDateBulk_ValueChanged(object sender, EventArgs e)
        {
            if (tabMainCtrl.SelectedIndex == 10)
                chkBranchConnect.Checked = ((sender as DateTimePicker).Value.ToString("dd/MM/yyyy") == DateTime.Now.ToString("dd/MM/yyyy"));
        }

        #endregion

        #region Cake Report

        private void btnCakeReport_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    if (dtBranches == null)
                        dtBranches = DBHelper.GetBranches();
                    cmbCakeBranches.DataSource = dtBranches;
                    cmbCakeBranches.DisplayMember = "BranchName";
                    cmbCakeBranches.ValueMember = "BranchID";
                    tabMainCtrl.SelectTab(11);

                    cmbCakeCategory.SelectedIndex = 0;
                    dtpCakeReport.Value = SelectedDate;
                    chkCakeReport.Checked = IsCheckedMontly;
                    cmbCakeBranches.SelectedIndex = BranchIndex;
                    chkCancelledCakes.Checked = false;

                    dgvBookedCakeReport.DataSource = null;
                    dgvDeliveredCakeReport.DataSource = null;
                    lblBkdCakeResult.Text = lblDlvCakeReport.Text = string.Empty;
                }
                catch (Exception)
                {
                    MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabMainCtrl.SelectTab(22);
                txtUserName.Focus();
            }
        }

        private void btnFetchCakeReport_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                BranchIndex = cmbCakeBranches.SelectedIndex;
                SelectedDate = dtpCakeReport.Value;
                IsCheckedMontly = chkCakeReport.Checked;
                bool IsException = false;

                //DataSet ds = DBHelper.GetCakesReport(cmbCakeBranches.SelectedValue.ToString(), dtpCakeReport.Value, chkCakeReport.Checked, chkCancelledCakes.Checked, out IsException);
                DataSet ds = DBHelper.GetCakesReport(cmbCakeBranches.SelectedValue.ToString(), dtpCakeReport.Value, chkCakeReport.Checked, cmbCakeCategory.Text, out IsException);

                if (IsException)
                {
                    dgvBookedCakeReport.DataSource = null;
                    dgvDeliveredCakeReport.DataSource = null;
                    MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (ds != null)
                {
                    dgvBookedCakeReport.DataSource = ds.Tables[0];
                    dgvBookedCakeReport.Columns[0].Width = 80;
                    lblBkdCakeResult.Text = "Advance: " + ds.Tables[1].Rows[0]["Advance"].ToString() + "                " + "Qty: " + ds.Tables[1].Rows[0]["Qty"].ToString() + " Kgs";

                    dgvDeliveredCakeReport.DataSource = ds.Tables[2];
                    dgvDeliveredCakeReport.Columns[0].Width = 80;
                    lblDlvCakeReport.Text = "Balance: " + ds.Tables[3].Rows[0]["Balance"].ToString() + "                " + "Qty: " + ds.Tables[3].Rows[0]["Qty"].ToString() + " Kgs";
                }
                else
                {
                    dgvBookedCakeReport.DataSource = null;
                    dgvDeliveredCakeReport.DataSource = null;
                    MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void chkUnDeliveredCakes_CheckedChanged(object sender, EventArgs e)
        {
            if (chkCancelledCakes.Checked)
                chkCancelledCakes.Checked = false;
            //chkUnDeliveredCakes.Checked = true;
        }

        private void chkCancelledCakes_CheckedChanged(object sender, EventArgs e)
        {
            if (chkUnDeliveredCakes.Checked)
                chkUnDeliveredCakes.Checked = false;
            //chkCancelledCakes.Checked = true;
        }

        private void dtpCakeReport_ValueChanged(object sender, EventArgs e)
        {
            if (tabMainCtrl.SelectedIndex == 11)
                chkBranchConnect.Checked = ((sender as DateTimePicker).Value.ToString("dd/MM/yyyy") == DateTime.Now.ToString("dd/MM/yyyy"));
        }

        #endregion

        #region Login Report

        private void btnLoginRep_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    if (dtBranches == null)
                        dtBranches = DBHelper.GetBranches();
                    cmbLoginBranch.DataSource = dtBranches;
                    cmbLoginBranch.DisplayMember = "BranchName";
                    cmbLoginBranch.ValueMember = "BranchID";
                    tabMainCtrl.SelectTab(12);
                    chkBranchConnect.Checked = true;
                }
                catch (Exception)
                {
                    MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabMainCtrl.SelectTab(22);
                txtUserName.Focus();
            }
        }

        private void btnFetchLogins_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                chkBranchConnect.Checked = true;
                SelectedDate = dtpLoginDate.Value;
                BranchIndex = cmbLoginBranch.SelectedIndex;
                chkBranchConnect.Checked = true;

                dgLoginReport.DataSource = DBHelper.GetLoginsByBranch(cmbLoginBranch.SelectedValue.ToString(), dtpLoginDate.Value);

                if (dgLoginReport.DataSource == null)
                {
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dtpLoginDate_ValueChanged(object sender, EventArgs e)
        {
            //if (tabMainCtrl.SelectedIndex == 12)
            //{
            //    chkBranchConnect.Checked = ((sender as DateTimePicker).Value.ToString("dd/MM/yyyy") == DateTime.Now.ToString("dd/MM/yyyy"));
            //    if (!chkBranchConnect.Checked)
            //        MessageBox.Show("There is no Login data available at Server");
            //}
        }

        #endregion

        #region Itemwise Report

        private void btnItemWise_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    if (dtBranchesAll == null)
                    {
                        dtBranchesAll = DBHelper.GetBranches();
                        dtBranchesAll.Rows.Add(0, "All");
                    }
                    cmbItemWiseBranch.DataSource = dtBranchesAll;
                    cmbItemWiseBranch.DisplayMember = "BranchName";
                    cmbItemWiseBranch.ValueMember = "BranchID";
                    tabMainCtrl.SelectTab(13);

                    dtpItemWise.Value = SelectedDate;
                    chkMonth.Checked = IsCheckedMontly;
                    cmbItemWiseBranch.SelectedIndex = BranchIndex;
                }
                catch (Exception)
                {
                    MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabMainCtrl.SelectTab(22);
                txtUserName.Focus();
            }
        }

        private void btnFetchItemWiseReport_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                if (cmbItemWiseBranch.SelectedValue.ToString() != "0")
                    BranchIndex = cmbItemWiseBranch.SelectedIndex;
                SelectedDate = dtpItemWise.Value;
                IsCheckedMontly = chkMonth.Checked;

                PrintDGV.IsMonthly = chkMonth.Checked;
                Branch = cmbItemWiseBranch.Text;
                Date = dtpItemWise.Value;

                //Branch - All - Not Possible
                if (cmbItemWiseBranch.SelectedValue.ToString() == "0" && chkBranchConnect.Checked)
                {
                    MessageBox.Show("Connecting to Branches cannot fetch Complete Data. Please change the Criteria.", "Invalid Criteria", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                dgvItemWiseReport.DataSource = DBHelper.GetItemWiseReportByBranch(cmbItemWiseBranch.SelectedValue.ToString(), dtpItemWise.Value, txtItem.Text, chkMonth.Checked);

                if (dgvItemWiseReport.DataSource == null)
                {
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    dgvItemWiseReport.Columns[0].Width = 50;
                    dgvItemWiseReport.Columns[1].Width = 250;
                    dgvItemWiseReport.Columns[2].Width = 80;
                    dgvItemWiseReport.Columns[3].Width = 80;
                    dgvItemWiseReport.Columns[4].Width = 80;
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnPrintItemWiseReport_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgvItemWiseReport.DataSource != null)
                {
                    PrintDGV.Branch = Branch;
                    PrintDGV.Date = Date;
                    PrintDGV.ReportType = "Itemwise Report";
                    PrintDGV.Print_DataGridView(dgvItemWiseReport);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dtpItemWise_ValueChanged(object sender, EventArgs e)
        {
            if (tabMainCtrl.SelectedIndex == 13)
                chkBranchConnect.Checked = ((sender as DateTimePicker).Value.ToString("dd/MM/yyyy") == DateTime.Now.ToString("dd/MM/yyyy"));
        }

        #endregion

        #region Deptwise Report

        private void btnDeptRept_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    if (dtBranchesAll == null)
                    {
                        dtBranchesAll = DBHelper.GetBranches();
                        dtBranchesAll.Rows.Add(0, "All");
                    }
                    cmbBranchDeptWise.DataSource = dtBranchesAll;
                    cmbBranchDeptWise.DisplayMember = "BranchName";
                    cmbBranchDeptWise.ValueMember = "BranchID";

                    DataTable dtDepts = DBHelper.GetDepartments();
                    dtDepts.Rows.Add("0", "All");
                    cmbDepartment.DataSource = dtDepts;
                    cmbDepartment.DisplayMember = "DeptName";
                    cmbDepartment.ValueMember = "DeptID";

                    tabMainCtrl.SelectTab(14);

                    dtpDeptWise.Value = SelectedDate;
                    chkDeptWiseMonth.Checked = IsCheckedMontly;
                    cmbBranchDeptWise.SelectedIndex = BranchIndex;
                }
                catch (Exception)
                {
                    MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabMainCtrl.SelectTab(22);
                txtUserName.Focus();
            }
        }

        private void btnDeptWiseReport_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                if (cmbBranchDeptWise.SelectedValue.ToString() != "0")
                    BranchIndex = cmbBranchDeptWise.SelectedIndex;
                SelectedDate = dtpDeptWise.Value;
                IsCheckedMontly = chkDeptWiseMonth.Checked;

                PrintDGV.IsMonthly = chkDeptWiseMonth.Checked;
                Branch = cmbBranchDeptWise.Text;
                Date = dtpDeptWise.Value;
                lblDept.Text = "Department : " + cmbDepartment.Text;

                //Branch - All - Not Possible
                if (cmbBranchDeptWise.SelectedValue.ToString() == "0" && chkBranchConnect.Checked)
                    MessageBox.Show("Connecting to Branches cannot fetch Complete Data. Please change the Criteria.", "Invalid Criteria", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                dgDeptWise.DataSource = DBHelper.GetDeptWiseReportByBranch(cmbBranchDeptWise.SelectedValue.ToString(), dtpDeptWise.Value, cmbDepartment.SelectedValue.ToString(), chkDeptWiseMonth.Checked);

                double ttlSales = 0;
                double ttlQty = 0;
                double temp = 0;
                foreach (DataGridViewRow row in dgDeptWise.Rows)
                {
                    if (double.TryParse(row.Cells[7].Value.ToString(), out temp))
                        ttlSales += temp;

                    if (double.TryParse(row.Cells[6].Value.ToString(), out temp))
                        ttlQty += temp;
                }

                lblTTLSales.Text = "Total Sales : " + ttlSales.ToString("c");
                lblTTLQty.Text = "Total Qty : " + ttlQty.ToString();

                if (dgDeptWise.DataSource == null)
                {
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    dgDeptWise.Columns[0].Width = 60;
                    dgDeptWise.Columns[1].Width = 250;
                    dgDeptWise.Columns[2].Visible = false;

                    if (cmbDepartment.SelectedValue.ToString() != "0")
                    {
                        dgDeptWise.Columns[3].Visible = false;
                    }
                    else
                    {
                        dgDeptWise.Columns[3].Visible = true;
                        dgDeptWise.Columns[3].Width = 150;
                    }

                    if (cmbBranchDeptWise.SelectedValue.ToString() != "0")
                    {
                        dgDeptWise.Columns[4].Visible = false;
                    }
                    else
                    {
                        dgDeptWise.Columns[4].Visible = true;
                        dgDeptWise.Columns[4].Width = 100;
                    }

                    dgDeptWise.Columns[5].Width = 80;
                    dgDeptWise.Columns[6].Width = 80;
                    dgDeptWise.Columns[7].Width = 80;
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnPrintDeptWise_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgDeptWise.DataSource != null)
                {
                    PrintDGV.Branch = Branch;
                    PrintDGV.Date = Date;
                    PrintDGV.ReportType = "Deptwise Report";
                    PrintDGV.Print_DataGridView(dgDeptWise);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dtpDeptWise_ValueChanged(object sender, EventArgs e)
        {
            if (tabMainCtrl.SelectedIndex == 14)
                chkBranchConnect.Checked = ((sender as DateTimePicker).Value.ToString("dd/MM/yyyy") == DateTime.Now.ToString("dd/MM/yyyy"));
        }

        #endregion

        #region Vendors Report

        private void btnVendors_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    if (dtBranches == null)
                        dtBranches = DBHelper.GetBranches();
                    cmbBranchVendor.DataSource = dtBranches;
                    cmbBranchVendor.DisplayMember = "BranchName";
                    cmbBranchVendor.ValueMember = "BranchID";
                    DataTable dtVendors = DBHelper.GetAllVendorsByBranch("0");
                    dtVendors.Rows.Add(0, "All");
                    cmbVendor.DataSource = dtVendors;
                    if (cmbVendor.DataSource != null)
                    {
                        cmbVendor.DisplayMember = "Vendor";
                        cmbVendor.ValueMember = "ID";
                    }
                    tabMainCtrl.SelectTab(15);

                    dpDateVendor.Value = SelectedDate;
                    chkCompleteMonthVendor.Checked = IsCheckedMontly;
                    cmbBranchVendor.SelectedIndex = BranchIndex;
                    dgVendors.DataSource = null;
                }
                catch (Exception)
                {
                    MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabMainCtrl.SelectTab(22);
                txtUserName.Focus();
            }
        }

        private void btnGetVendorBills_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                SelectedDate = dpDateVendor.Value;
                BranchIndex = cmbBranchVendor.SelectedIndex;
                IsCheckedMontly = chkCompleteMonthVendor.Checked;
                bool IsException = false;

                DataSet ds = DBHelper.GetVendorSales(cmbBranchVendor.SelectedValue.ToString(), dpDateVendor.Value, chkCompleteMonthVendor.Checked, cmbVendor.SelectedValue.ToString(), out IsException);

                if (IsException)
                {
                    dgVendors.DataSource = null;
                    MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (ds != null && ds.Tables.Count == 2)
                {
                    DataRow drTotal = ds.Tables[0].NewRow();
                    drTotal[0] = "TOTAL";
                    drTotal[2] = ds.Tables[1].Rows[0][0].ToString();
                    ds.Tables[0].Rows.Add(drTotal);

                    dgVendors.DataSource = ds.Tables[0];

                    Date = dpDateVendor.Value;
                    Branch = cmbBranchVendor.Text;
                    IsMonthly = chkCompleteMonthVendor.Checked;

                    if (dgVendors.DataSource != null)
                    {
                        dgVendors.Columns[0].Width = 250;
                        dgVendors.Columns[1].Width = 100;
                        dgVendors.Columns[2].Width = 100;
                    }
                }
                else
                {
                    dgVendors.DataSource = null;
                    MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnPrintVendorReport_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgVendors.DataSource != null)
                {
                    PrintDGV.Branch = Branch;
                    PrintDGV.Date = Date;
                    PrintDGV.IsMonthly = IsMonthly;
                    PrintDGV.ReportType = "Vendors Report";
                    PrintDGV.Print_DataGridView(dgVendors);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dpDateVendor_ValueChanged(object sender, EventArgs e)
        {
            if (tabMainCtrl.SelectedIndex == 15)
                chkBranchConnect.Checked = ((sender as DateTimePicker).Value.ToString("dd/MM/yyyy") == DateTime.Now.ToString("dd/MM/yyyy"));
        }

        #endregion

        #region Payments Report

        private void btnPayments_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    if (dtBranches == null)
                        dtBranches = DBHelper.GetBranches();
                    cmbVendorBranches.DataSource = dtBranches;
                    cmbVendorBranches.DisplayMember = "BranchName";
                    cmbVendorBranches.ValueMember = "BranchID";

                    cmbPaymentDates.DataSource = FillDates();
                    cmbPaymentDates.DisplayMember = "DateRange";
                    cmbPaymentDates.ValueMember = "Date";

                    tabMainCtrl.SelectTab(16);

                    //cmbSuppliers.DataSource = DBHelper.GetVendorSuppliers();
                    //cmbSuppliers.DisplayMember = "SupplierName";
                    //cmbSuppliers.ValueMember = "SupplierID";

                    cmbSuppliers.DataSource = DBHelper.GetVendorSuppliers();
                    cmbSuppliers.DisplayMember = "Vendor";
                    cmbSuppliers.ValueMember = "ID";

                    //dpDateVendor.Value = SelectedDate;
                    //chkCompleteMonthVendor.Checked = IsCheckedMontly;
                    cmbVendorBranches.SelectedIndex = BranchIndex;
                    dgvPayments.DataSource = null;
                }
                catch (Exception)
                {
                    MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabMainCtrl.SelectTab(22);
                txtUserName.Focus();
            }
        }

        private DataTable FillDates()
        {
            try
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("DateRange");
                dt.Columns.Add("Date");
                DateTime date = DateTime.Now;

                //for (int cnt = -11; cnt <= 0; cnt++)
                for (int cnt = 0; cnt > -11; cnt--)
                {
                    date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                    date = date.AddMonths(cnt);

                    DataRow row1 = dt.NewRow();
                    row1[0] = "16 " + date.ToString("MMM yyyy") + " - " + date.AddMonths(1).AddDays(-1).ToString("dd MMM yyyy");
                    row1[1] = new DateTime(date.Year, date.Month, 16);
                    dt.Rows.Add(row1);

                    DataRow row = dt.NewRow();
                    row[0] = "1  " + date.ToString("MMM yyyy") + "  -  " + "15 " + date.ToString("MMM yyyy");
                    row[1] = new DateTime(date.Year, date.Month, 1);
                    dt.Rows.Add(row);
                }

                return dt;
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }

        private void btnFetchBills_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                paymentSupplier = cmbSuppliers.SelectedValue.ToString();
                paymentBranch = cmbVendorBranches.SelectedValue.ToString();
                paymentDate = cmbPaymentDates.SelectedValue.ToString();

                DataTable dtValues = DBHelper.GetSelectedMonthPaymentDataByBranchAndSupplier(cmbPaymentDates.SelectedValue.ToString(), cmbVendorBranches.SelectedValue.ToString(), cmbSuppliers.SelectedValue.ToString());

                if (dtValues != null && dtValues.Rows.Count > 0)
                {
                    btnSaveDetails.Enabled = false;
                    btnSaveVendorBills.Enabled = false;
                    txtAmountPaid.Enabled = false;

                    lblPreviousBalance.Text = dtValues.Rows[0]["CarryForwarded"].ToString();
                    lblBillsAmount.Text = dtValues.Rows[0]["BillAmount"].ToString();
                    txtAmountPaid.Text = dtValues.Rows[0]["AmountPaid"].ToString();
                    lblForwardBalance.Text = dtValues.Rows[0]["Balance"].ToString();
                }
                else
                {
                    btnSaveDetails.Enabled = true;
                    btnSaveVendorBills.Enabled = true;
                    txtAmountPaid.Enabled = true;
                }

                DataSet ds = DBHelper.GetBillsByBranchAndPreviousBalance(cmbPaymentDates.SelectedValue.ToString(), cmbVendorBranches.SelectedValue.ToString(), cmbSuppliers.SelectedValue.ToString());
                dgvPayments.DataSource = ds.Tables[0];
                if (dgvPayments.DataSource != null)
                {
                    dgvPayments.Columns[0].Width = 60;
                    dgvPayments.Columns[0].ReadOnly = true;
                    dgvPayments.Columns[1].Visible = false;
                    dgvPayments.Columns[2].Width = 100;
                    dgvPayments.Columns[2].ReadOnly = true;
                    dgvPayments.Columns[3].Width = 100;
                    dgvPayments.Columns[3].ReadOnly = true;
                    dgvPayments.Columns[4].Width = 100;
                    dgvPayments.Columns[4].ReadOnly = true;
                    dgvPayments.Columns[5].Width = 60;
                }

                if (btnSaveDetails.Enabled)
                {
                    txtAmountPaid.Clear();
                    if (ds.Tables[1] != null && ds.Tables[1].Rows.Count > 0)
                        lblPreviousBalance.Text = ds.Tables[1].Rows[0][0].ToString();
                    else
                        lblPreviousBalance.Text = "0";

                    Calculate();
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSaveVendorBills_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (DataGridViewRow row in dgvPayments.Rows)
                {
                    int res = DBHelper.UpdateSupplierBill(row.Cells[0].Value.ToString(), bool.Parse(row.Cells[4].Value.ToString()));
                    if (res <= 0)
                        throw new Exception();
                }
                //btnFetchBills_Click(sender, e);
                Calculate();
                MessageBox.Show("Updated Successfully", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred While Updating", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Calculate()
        {
            try
            {
                if (btnSaveDetails.Enabled)
                {
                    double payment = 0.0d;
                    foreach (DataGridViewRow row in dgvPayments.Rows)
                    {
                        if (bool.Parse(row.Cells[5].Value.ToString()))
                            payment += double.Parse(row.Cells[3].Value.ToString());
                    }
                    lblBillsAmount.Text = payment.ToString();

                    double previousBal = double.Parse(lblPreviousBalance.Text);
                    double amountPaid = 0.0d;

                    try
                    {
                        amountPaid = double.Parse(txtAmountPaid.Text);
                    }
                    catch { }

                    lblForwardBalance.Text = (payment + previousBal - amountPaid).ToString();
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtAmountPaid_TextChanged(object sender, EventArgs e)
        {
            try
            {
                double amt = 0.0d;
                if (!double.TryParse(txtAmountPaid.Text, out amt))
                {
                    txtAmountPaid.Clear();
                }
                Calculate();
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSaveDetails_Click(object sender, EventArgs e)
        {
            try
            {
                int result = DBHelper.SavePaymentDetails(paymentBranch, paymentSupplier, paymentDate, lblPreviousBalance.Text, lblBillsAmount.Text, txtAmountPaid.Text, lblForwardBalance.Text);
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Sales Report

        private void btnSalesReport_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    DataTable dtDepts = DBHelper.GetDepartments();
                    DataRow row = dtDepts.NewRow();
                    row[0] = 0;
                    row[1] = "CAKES";
                    dtDepts.Rows.InsertAt(row, 0);
                    dtDepts.Rows.RemoveAt(7);
                    dtDepts.Rows.RemoveAt(7);
                    cmbDeptSalesReport.DataSource = dtDepts;
                    cmbDeptSalesReport.DisplayMember = "DeptName";
                    cmbDeptSalesReport.ValueMember = "DeptID";

                    tabMainCtrl.SelectTab(17);
                }
                catch (Exception)
                {
                    MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabMainCtrl.SelectTab(22);
                txtUserName.Focus();
            }
        }

        private void btnFetchSalesReport_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                chkBranchConnect.Checked = false;
                SelectedDate = dtpSalesReportDate.Value;
                IsCheckedMontly = chkMonthlySalesReport.Checked;
                PrintDGV.IsMonthly = chkMonthlySalesReport.Checked;
                Date = dtpDeptWise.Value;
                lblDept.Text = "Department : " + cmbDepartment.Text;
                PrintDGV.Department = cmbDeptSalesReport.Text;

                dgSalesReport.DataSource = DBHelper.GetSalesReport(dtpSalesReportDate.Value, chkMonthlySalesReport.Checked, cmbDeptSalesReport.SelectedValue.ToString());
                if (dgSalesReport.DataSource != null)
                {
                    dgSalesReport.Columns[0].HeaderText = string.Empty;
                    dgSalesReport.Columns[1].HeaderText = "CHANDANAGAR";
                    dgSalesReport.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader;
                    dgSalesReport.Columns[2].HeaderText = "MIYAPUR";
                    dgSalesReport.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader;
                    dgSalesReport.Columns[3].HeaderText = "KUKATPALLY";
                    dgSalesReport.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader;
                    dgSalesReport.Columns[4].HeaderText = "AMEERPET";
                    dgSalesReport.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader;
                    dgSalesReport.Columns[5].HeaderText = "JNTU";
                    dgSalesReport.Columns[5].AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader;
                    if (dgSalesReport.Columns.Count > 6)
                        dgSalesReport.Columns[6].HeaderText = "TOTAL";
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgSalesReport.DataSource != null)
                {
                    //PrintDGV.Branch = Branch;
                    PrintDGV.Date = Date;
                    PrintDGV.ReportType = "Sales Report";
                    PrintDGV.Print_DataGridView(dgSalesReport);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region CreditNote Payments

        private void btnCreditPayments_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    if (dtBranches == null)
                        dtBranches = DBHelper.GetBranches();
                    cmbCreditNoteBranches.DataSource = dtBranches;
                    cmbCreditNoteBranches.DisplayMember = "BranchName";
                    cmbCreditNoteBranches.ValueMember = "BranchID";

                    cmbCreditNoteDates.DataSource = FillDates();
                    cmbCreditNoteDates.DisplayMember = "DateRange";
                    cmbCreditNoteDates.ValueMember = "Date";

                    tabMainCtrl.SelectTab(18);

                    cmbCreditNoteCompany.DataSource = DBHelper.GetVendorSuppliers();
                    cmbCreditNoteCompany.DisplayMember = "Vendor";
                    cmbCreditNoteCompany.ValueMember = "ID";

                    //dpDateVendor.Value = SelectedDate;
                    //chkCompleteMonthVendor.Checked = IsCheckedMontly;
                    cmbCreditNoteBranches.SelectedIndex = BranchIndex;
                    dgvCreditNotes.DataSource = null;
                }
                catch (Exception)
                {
                    MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabMainCtrl.SelectTab(22);
                txtUserName.Focus();
            }
        }

        private void btnFetchCreditNoteDetails_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                paymentSupplier = cmbCreditNoteCompany.SelectedValue.ToString();
                paymentBranch = cmbCreditNoteBranches.SelectedValue.ToString();
                paymentDate = cmbCreditNoteDates.SelectedValue.ToString();

                DataTable dtValues = DBHelper.GetSelectedMonthCreditNoteDataByBranchAndCompany(cmbCreditNoteDates.SelectedValue.ToString(), cmbCreditNoteBranches.SelectedValue.ToString(), cmbCreditNoteCompany.SelectedValue.ToString());

                if (dtValues != null && dtValues.Rows.Count > 0)
                {
                    btnCreditNoteSaveDetails.Enabled = false;
                    btnSaveCreditNotes.Enabled = false;
                    txtCreditNoteAmountPaid.Enabled = false;

                    lblCreditNotePreviousBalance.Text = dtValues.Rows[0]["CarryForwarded"].ToString();
                    lblCreditNoteBillsAmount.Text = dtValues.Rows[0]["BillAmount"].ToString();
                    txtCreditNoteAmountPaid.Text = dtValues.Rows[0]["AmountPaid"].ToString();
                    lblCreditNoteForwardBalance.Text = dtValues.Rows[0]["Balance"].ToString();
                }
                else
                {
                    btnCreditNoteSaveDetails.Enabled = true;
                    btnSaveCreditNotes.Enabled = true;
                    txtCreditNoteAmountPaid.Enabled = true;
                }

                dgvCreditNotes.DataSource = DBHelper.GetCreditNotesByBranchAndPreviousBalance(cmbCreditNoteDates.SelectedValue.ToString(), cmbCreditNoteBranches.SelectedValue.ToString(), cmbCreditNoteCompany.SelectedValue.ToString());
                if (dgvCreditNotes.DataSource != null)
                {
                    dgvCreditNotes.Columns[0].Width = 40;
                    dgvCreditNotes.Columns[0].ReadOnly = true;
                    dgvCreditNotes.Columns[1].Width = 60;
                    dgvCreditNotes.Columns[1].ReadOnly = true;
                    dgvCreditNotes.Columns[2].Width = 100;
                    dgvCreditNotes.Columns[2].ReadOnly = true;
                    dgvCreditNotes.Columns[3].Width = 100;
                    dgvCreditNotes.Columns[3].ReadOnly = true;
                    dgvCreditNotes.Columns[4].Width = 100;
                    //dgvCreditNotes.Columns[4].ReadOnly = true;
                    //dgvCreditNotes.Columns[5].Width = 60;
                }

                DataTable dtV = DBHelper.GetCreditNotesPreviousBalance(cmbCreditNoteDates.SelectedValue.ToString(), cmbCreditNoteBranches.SelectedValue.ToString(), cmbCreditNoteCompany.SelectedValue.ToString());

                if (btnCreditNoteSaveDetails.Enabled)
                {
                    txtCreditNoteAmountPaid.Clear();
                    if (dtV != null && dtV.Rows.Count > 0)
                        lblCreditNotePreviousBalance.Text = dtV.Rows[0][0].ToString();
                    else
                        lblCreditNotePreviousBalance.Text = "0";

                    CalculateCreditNote();
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void CalculateCreditNote()
        {
            try
            {
                if (btnCreditNoteSaveDetails.Enabled)
                {
                    double payment = 0.0d;
                    foreach (DataGridViewRow row in dgvCreditNotes.Rows)
                    {
                        if (!(bool.Parse(row.Cells[4].Value.ToString())))
                            payment += double.Parse(row.Cells[2].Value.ToString());
                    }
                    lblCreditNoteBillsAmount.Text = payment.ToString();

                    double previousBal = double.Parse(lblCreditNotePreviousBalance.Text);
                    double amountPaid = 0.0d;

                    try
                    {
                        amountPaid = double.Parse(txtCreditNoteAmountPaid.Text);
                    }
                    catch { }

                    lblCreditNoteForwardBalance.Text = (payment + previousBal - amountPaid).ToString();
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtCreditNoteAmountPaid_TextChanged(object sender, EventArgs e)
        {
            try
            {
                double amt = 0.0d;
                if (!double.TryParse(txtCreditNoteAmountPaid.Text, out amt))
                {
                    txtCreditNoteAmountPaid.Clear();
                }
                CalculateCreditNote();
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSaveCreditNotes_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (DataGridViewRow row in dgvCreditNotes.Rows)
                {
                    int res = DBHelper.UpdateCreditNoteBill(row.Cells[1].Value.ToString(), bool.Parse(row.Cells[4].Value.ToString()));
                    if (res <= 0)
                        throw new Exception();
                }
                CalculateCreditNote();
                MessageBox.Show("Updated Successfully", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred While Updating", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCreditNoteSaveDetails_Click(object sender, EventArgs e)
        {
            try
            {
                int result = DBHelper.SaveCreditNotePaymentDetails(paymentBranch, paymentSupplier, paymentDate, lblCreditNotePreviousBalance.Text, lblCreditNoteBillsAmount.Text, txtCreditNoteAmountPaid.Text, lblCreditNoteForwardBalance.Text);
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Quarterly Report

        private void btnQuarterlyReport_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    if (dtBranches == null)
                        dtBranches = DBHelper.GetBranches();
                    cmbQBranch.DataSource = dtBranches;
                    cmbQBranch.DisplayMember = "BranchName";
                    cmbQBranch.ValueMember = "BranchID";
                    chkBranchConnect.Checked = false;
                    cmbQMonth.SelectedIndex = 0;
                    cmbQYear.SelectedIndex = DateTime.Now.Year - 2011;
                    tabMainCtrl.SelectTab(19);
                    dgvQuarterlyReport.DataSource = null;

                    lblPOSSalesQuarterly.Text = "POS Sales: ";
                    lblCakeSalesQuarterly.Text = "Cake Sales: ";
                    lblBulkOrdersQuarterly.Text = "Bulk Orders: ";
                    lblDiscountQuarterly.Text = "Discount: ";
                    lblTotalSalesQuarterly.Text = "Total Sales: ";
                    lblExpensesQuarterly.Text = "Expenses: ";
                    lblSodexhoSalesQuarterly.Text = "Sodexho Sales: ";
                    lblCardSalesQuarterly.Text = "Card Sales: ";
                    lblEmpAdvanceBillQuarterly.Text = "Emp Advance/Bill Amounts: ";
                    lblCreditNoteAmountQuarterly.Text = "Credit Note Amount: ";
                    lblCashAvailableQuarterly.Text = "Cash Available: ";
                }
                catch (Exception)
                {
                    MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabMainCtrl.SelectTab(22);
                txtUserName.Focus();
            }
        }

        private void btnGetQReport_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                Branch = cmbQBranch.Text;
                PrintDGV.QuarterlyMonths = cmbQMonth.Text + " " + cmbQYear.Text;
                DateTime fromDate = DateTime.MinValue;
                DateTime toDate = DateTime.MinValue;

                if (cmbQMonth.Text == "Jan - Mar")
                {
                    fromDate = new DateTime(int.Parse(cmbQYear.Text), 1, 1);
                    toDate = new DateTime(int.Parse(cmbQYear.Text), 3, 1).AddMonths(1).AddDays(-1);
                }
                else if (cmbQMonth.Text == "Apr - Jun")
                {
                    fromDate = new DateTime(int.Parse(cmbQYear.Text), 4, 1);
                    toDate = new DateTime(int.Parse(cmbQYear.Text), 6, 1).AddMonths(1).AddDays(-1);
                }
                else if (cmbQMonth.Text == "Jul - Sep")
                {
                    fromDate = new DateTime(int.Parse(cmbQYear.Text), 7, 1);
                    toDate = new DateTime(int.Parse(cmbQYear.Text), 9, 1).AddMonths(1).AddDays(-1);
                }
                else if (cmbQMonth.Text == "Oct - Dec")
                {
                    fromDate = new DateTime(int.Parse(cmbQYear.Text), 10, 1);
                    toDate = new DateTime(int.Parse(cmbQYear.Text), 12, 1).AddMonths(1).AddDays(-1);
                }

                if (cmbQBranch.SelectedIndex < 5)
                    BranchIndex = cmbQBranch.SelectedIndex;

                DataSet dsResult = DBHelper.GetAcemadicReport(fromDate, toDate, cmbQBranch.SelectedValue.ToString());

                double cakeSales = 0d;
                double discounts = 0d;
                double totalSales = 0d;
                double expenseAmt = 0d;
                double sodexhoAmt = 0d;
                double creditCardAmt = 0d;
                double salariesAmt = 0d;
                double creditNoteAmount = 0d;
                double bulkOrdersAmt = 0d;

                if (dsResult != null)
                {
                    //POS Sales
                    DataRow drSales = dsResult.Tables[0].NewRow();
                    drSales[1] = "POS SALES";
                    drSales[3] = dsResult.Tables[1].Rows[0]["POSSales"].ToString();
                    dsResult.Tables[0].Rows.Add(drSales);

                    //Cake Sales
                    double tmpValue = 0d;

                    if (double.TryParse(dsResult.Tables[2].Rows[0]["Advance"].ToString(), out tmpValue))
                        cakeSales += tmpValue;
                    if (double.TryParse(dsResult.Tables[3].Rows[0]["Balance"].ToString(), out tmpValue))
                        cakeSales += tmpValue;

                    DataRow drCakeSales = dsResult.Tables[0].NewRow();
                    drCakeSales[1] = "CAKE SALES";
                    drCakeSales[3] = cakeSales.ToString();
                    dsResult.Tables[0].Rows.Add(drCakeSales);

                    //Discount
                    tmpValue = 0d;

                    if (dsResult.Tables[1].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[1].Rows[0]["POSDiscounts"].ToString(), out tmpValue))
                            discounts += tmpValue;
                    }

                    if (dsResult.Tables[2].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[2].Rows[0]["CakeDiscounts"].ToString(), out tmpValue))
                            discounts += tmpValue;
                    }

                    DataRow drDiscount = dsResult.Tables[0].NewRow();
                    drDiscount[1] = "DISCOUNT";
                    drDiscount[3] = Math.Round(discounts, 2);
                    dsResult.Tables[0].Rows.Add(drDiscount);

                    //Vendor Sales
                    double vendorSales = 0d;

                    double.TryParse(dsResult.Tables[7].Rows[0]["VendorSales"].ToString(), out vendorSales);
                    DataRow drVendorSales = dsResult.Tables[0].NewRow();
                    drVendorSales[1] = "VENDOR SALES";
                    drVendorSales[3] = vendorSales.ToString();
                    dsResult.Tables[0].Rows.Add(drVendorSales);

                    if (dsResult.Tables[8] != null && dsResult.Tables[8].Rows.Count > 0)
                    {
                        double.TryParse(dsResult.Tables[8].Rows[0]["BulkOrderAdvance"].ToString(), out tmpValue);
                        bulkOrdersAmt += tmpValue;
                    }

                    if (dsResult.Tables[9] != null && dsResult.Tables[9].Rows.Count > 0)
                    {
                        double.TryParse(dsResult.Tables[9].Rows[0]["BulkOrderBalance"].ToString(), out tmpValue);
                        bulkOrdersAmt += tmpValue;
                    }

                    DataRow drBulkOrder = dsResult.Tables[0].NewRow();
                    drBulkOrder[1] = "BULK ORDERS";
                    drBulkOrder[3] = bulkOrdersAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drBulkOrder);

                    //Total Sales
                    tmpValue = 0d;

                    if (dsResult.Tables[1].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[1].Rows[0]["POSSales"].ToString(), out tmpValue))
                            totalSales += tmpValue;
                    }
                    totalSales += cakeSales;
                    totalSales += bulkOrdersAmt;

                    DataRow drTotalSales = dsResult.Tables[0].NewRow();
                    drTotalSales[1] = "TOTAL SALES";
                    drTotalSales[3] = (totalSales - discounts + creditNoteAmount).ToString();
                    dsResult.Tables[0].Rows.Add(drTotalSales);

                    //Expense Amounts
                    tmpValue = 0d;

                    if (dsResult.Tables[4].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[4].Rows[0]["ExpenseAmount"].ToString(), out tmpValue))
                            expenseAmt = tmpValue;
                    }

                    DataRow drExpense = dsResult.Tables[0].NewRow();
                    drExpense[1] = "EXPENSE AMOUNT";
                    drExpense[3] = expenseAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drExpense);

                    //Sodexho Amount
                    tmpValue = 0d;

                    if (dsResult.Tables[5].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[5].Rows[0]["SodexhoAmount"].ToString(), out tmpValue))
                            sodexhoAmt = tmpValue;
                    }

                    DataRow drSodexho = dsResult.Tables[0].NewRow();
                    drSodexho[1] = "SODEXHO AMOUNT";
                    drSodexho[3] = sodexhoAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drSodexho);

                    //CreditCard Amount
                    tmpValue = 0d;

                    if (dsResult.Tables[5].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[5].Rows[0]["CreditCardAmount"].ToString(), out tmpValue))
                            creditCardAmt = tmpValue;
                    }

                    DataRow drCard = dsResult.Tables[0].NewRow();
                    drCard[1] = "CREDITCARD AMOUNT";
                    drCard[3] = creditCardAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drCard);

                    //Get Advances & Bill from Salaries Application
                    salariesAmt = DBHelper.GetEmpAdvancesandBillsForMonth(fromDate, toDate, cmbQBranch.SelectedValue.ToString());

                    DataRow drSalariesApp = dsResult.Tables[0].NewRow();
                    drSalariesApp[1] = "EMP ADVANCES/BILLS";
                    drSalariesApp[3] = salariesAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drSalariesApp);

                    if (dsResult.Tables[6].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[6].Rows[0]["CreditNoteAmount"].ToString(), out tmpValue))
                            creditNoteAmount = tmpValue;
                    }

                    //Credit Note Amount
                    DataRow drCreditNoteAmount = dsResult.Tables[0].NewRow();
                    drCreditNoteAmount[1] = "CREDIT NOTES AMOUNT";
                    drCreditNoteAmount[3] = creditNoteAmount;
                    dsResult.Tables[0].Rows.Add(drCreditNoteAmount);

                    //Available Cash
                    DataRow drAvailableCash = dsResult.Tables[0].NewRow();
                    drAvailableCash[1] = "AVAILABLE CASH";
                    drAvailableCash[3] = Math.Round(totalSales - discounts - expenseAmt - sodexhoAmt - creditCardAmt - salariesAmt, 2);
                    dsResult.Tables[0].Rows.Add(drAvailableCash);

                    dgvQuarterlyReport.DataSource = dsResult.Tables[0];
                    dgvQuarterlyReport.Columns[0].Width = 80;
                    dgvQuarterlyReport.Columns[1].Width = 170;
                    dgvQuarterlyReport.Columns[2].Width = 70;
                    dgvQuarterlyReport.Columns[3].Width = 100;

                    lblPOSSalesQuarterly.Text = "POS Sales: " + dsResult.Tables[1].Rows[0]["POSSales"].ToString();
                    lblCakeSalesQuarterly.Text = "Cake Sales: " + cakeSales.ToString();
                    lblDiscountQuarterly.Text = "Discount: " + discounts.ToString();
                    lblTotalSalesQuarterly.Text = "Total Sales: " + (totalSales - discounts + creditNoteAmount).ToString();
                    lblExpensesQuarterly.Text = "Expenses: " + expenseAmt.ToString();
                    lblSodexhoSalesQuarterly.Text = "Sodexho Sales: " + sodexhoAmt.ToString();
                    lblCardSalesQuarterly.Text = "Card Sales: " + creditCardAmt.ToString();
                    lblEmpAdvanceBillQuarterly.Text = "Emp Advance/Bill Amounts: " + salariesAmt.ToString();
                    lblCreditNoteAmountQuarterly.Text = "Credit Note Amount: " + creditNoteAmount.ToString();
                    lblCashAvailableQuarterly.Text = "Cash Available: " + Math.Round((totalSales - discounts - expenseAmt - sodexhoAmt - creditCardAmt - salariesAmt), 2).ToString();
                    lblBulkOrdersQuarterly.Text = "Bulk Orders: " + Math.Round(bulkOrdersAmt, 2).ToString();
                }
                else
                {
                    dgvQuarterlyReport.DataSource = null;
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                dgvQuarterlyReport.DataSource = null;
                lblPOSSalesQuarterly.Text = "POS Sales: ";
                lblCakeSalesQuarterly.Text = "Cake Sales: ";
                lblDiscountQuarterly.Text = "Discount: ";
                lblTotalSalesQuarterly.Text = "Total Sales: ";
                lblExpensesQuarterly.Text = "Expenses: ";
                lblSodexhoSalesQuarterly.Text = "Sodexho Sales: ";
                lblCardSalesQuarterly.Text = "Card Sales: ";
                lblEmpAdvanceBillQuarterly.Text = "Emp Advance/Bill Amounts: ";
                lblCreditNoteAmountQuarterly.Text = "Credit Note Amount: ";
                lblCashAvailableQuarterly.Text = "Cash Available: ";
                lblBulkOrdersQuarterly.Text = "Bulk Orders: ";
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void lblPrintQuarterlyReport_Click(object sender, EventArgs e)
        {
            if (dgvQuarterlyReport.DataSource != null)
            {
                PrintDGV.Branch = Branch;
                PrintDGV.ReportType = "Quarterly Report";
                PrintDGV.Print_DataGridView(dgvQuarterlyReport);
            }
        }

        #endregion

        #region HalfYearly Report

        private void btnHalfYearly_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    if (dtBranches == null)
                        dtBranches = DBHelper.GetBranches();
                    cmbHBranch.DataSource = dtBranches;
                    cmbHBranch.DisplayMember = "BranchName";
                    cmbHBranch.ValueMember = "BranchID";
                    chkBranchConnect.Checked = false;
                    cmbHMonth.SelectedIndex = 0;
                    cmbHYear.SelectedIndex = DateTime.Now.Year - 2011;
                    tabMainCtrl.SelectTab(20);
                    dgvHalfReport.DataSource = null;

                    tabMainCtrl.Text = "POS Sales: ";
                    lblCakeSalesHalf.Text = "Cake Sales: ";
                    lblBulkOrdersHalf.Text = "Bulk Orders: ";
                    lblDiscountHalf.Text = "Discount: ";
                    lblTotalSalesHalf.Text = "Total Sales: ";
                    lblExpensesHalf.Text = "Expenses: ";
                    lblSodexhoSalesHalf.Text = "Sodexho Sales: ";
                    lblCardSalesHalf.Text = "Card Sales: ";
                    lblEmpAdvanceBillHalf.Text = "Emp Advance/Bill Amounts: ";
                    lblCreditNoteAmountHalf.Text = "Credit Note Amount: ";
                    lblCashAvailableHalf.Text = "Cash Available: ";
                }
                catch (Exception)
                {
                    MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabMainCtrl.SelectTab(22);
                txtUserName.Focus();
            }
        }

        private void btnHGetData_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                Branch = cmbHBranch.Text;
                PrintDGV.YearlyMonths = cmbHMonth.Text + " " + cmbHYear.Text;
                DateTime fromDate = DateTime.MinValue;
                DateTime toDate = DateTime.MinValue;

                if (cmbHMonth.Text == "Jan - Jun")
                {
                    fromDate = new DateTime(int.Parse(cmbHYear.Text), 1, 1);
                    toDate = new DateTime(int.Parse(cmbHYear.Text), 6, 1).AddMonths(1).AddDays(-1);
                }
                else if (cmbHMonth.Text == "Jul - Dec")
                {
                    fromDate = new DateTime(int.Parse(cmbHYear.Text), 7, 1);
                    toDate = new DateTime(int.Parse(cmbHYear.Text), 12, 1).AddMonths(1).AddDays(-1);
                }

                if (cmbHBranch.SelectedIndex < 5)
                    BranchIndex = cmbHBranch.SelectedIndex;

                DataSet dsResult = DBHelper.GetAcemadicReport(fromDate, toDate, cmbHBranch.SelectedValue.ToString());

                double cakeSales = 0d;
                double discounts = 0d;
                double totalSales = 0d;
                double expenseAmt = 0d;
                double sodexhoAmt = 0d;
                double creditCardAmt = 0d;
                double salariesAmt = 0d;
                double creditNoteAmount = 0d;
                double bulkOrdersAmt = 0d;

                if (dsResult != null)
                {
                    //POS Sales
                    DataRow drSales = dsResult.Tables[0].NewRow();
                    drSales[1] = "POS SALES";
                    drSales[3] = dsResult.Tables[1].Rows[0]["POSSales"].ToString();
                    dsResult.Tables[0].Rows.Add(drSales);

                    //Cake Sales
                    double tmpValue = 0d;

                    if (double.TryParse(dsResult.Tables[2].Rows[0]["Advance"].ToString(), out tmpValue))
                        cakeSales += tmpValue;
                    if (double.TryParse(dsResult.Tables[3].Rows[0]["Balance"].ToString(), out tmpValue))
                        cakeSales += tmpValue;

                    DataRow drCakeSales = dsResult.Tables[0].NewRow();
                    drCakeSales[1] = "CAKE SALES";
                    drCakeSales[3] = cakeSales.ToString();
                    dsResult.Tables[0].Rows.Add(drCakeSales);

                    //Discount
                    tmpValue = 0d;

                    if (dsResult.Tables[1].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[1].Rows[0]["POSDiscounts"].ToString(), out tmpValue))
                            discounts += tmpValue;
                    }

                    if (dsResult.Tables[2].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[2].Rows[0]["CakeDiscounts"].ToString(), out tmpValue))
                            discounts += tmpValue;
                    }

                    DataRow drDiscount = dsResult.Tables[0].NewRow();
                    drDiscount[1] = "DISCOUNT";
                    drDiscount[3] = Math.Round(discounts, 2);
                    dsResult.Tables[0].Rows.Add(drDiscount);

                    //Vendor Sales
                    double vendorSales = 0d;

                    double.TryParse(dsResult.Tables[7].Rows[0]["VendorSales"].ToString(), out vendorSales);
                    DataRow drVendorSales = dsResult.Tables[0].NewRow();
                    drVendorSales[1] = "VENDOR SALES";
                    drVendorSales[3] = vendorSales.ToString();
                    dsResult.Tables[0].Rows.Add(drVendorSales);

                    if (dsResult.Tables[8] != null && dsResult.Tables[8].Rows.Count > 0)
                    {
                        double.TryParse(dsResult.Tables[8].Rows[0]["BulkOrderAdvance"].ToString(), out tmpValue);
                        bulkOrdersAmt += tmpValue;
                    }

                    if (dsResult.Tables[9] != null && dsResult.Tables[9].Rows.Count > 0)
                    {
                        double.TryParse(dsResult.Tables[9].Rows[0]["BulkOrderBalance"].ToString(), out tmpValue);
                        bulkOrdersAmt += tmpValue;
                    }

                    DataRow drBulkOrder = dsResult.Tables[0].NewRow();
                    drBulkOrder[1] = "BULK ORDERS";
                    drBulkOrder[3] = bulkOrdersAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drBulkOrder);

                    //Total Sales
                    tmpValue = 0d;

                    if (dsResult.Tables[1].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[1].Rows[0]["POSSales"].ToString(), out tmpValue))
                            totalSales += tmpValue;
                    }
                    totalSales += cakeSales;
                    totalSales += bulkOrdersAmt;

                    DataRow drTotalSales = dsResult.Tables[0].NewRow();
                    drTotalSales[1] = "TOTAL SALES";
                    drTotalSales[3] = (totalSales - discounts + creditNoteAmount).ToString();
                    dsResult.Tables[0].Rows.Add(drTotalSales);

                    //Expense Amounts
                    tmpValue = 0d;

                    if (dsResult.Tables[4].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[4].Rows[0]["ExpenseAmount"].ToString(), out tmpValue))
                            expenseAmt = tmpValue;
                    }

                    DataRow drExpense = dsResult.Tables[0].NewRow();
                    drExpense[1] = "EXPENSE AMOUNT";
                    drExpense[3] = expenseAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drExpense);

                    //Sodexho Amount
                    tmpValue = 0d;

                    if (dsResult.Tables[5].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[5].Rows[0]["SodexhoAmount"].ToString(), out tmpValue))
                            sodexhoAmt = tmpValue;
                    }

                    DataRow drSodexho = dsResult.Tables[0].NewRow();
                    drSodexho[1] = "SODEXHO AMOUNT";
                    drSodexho[3] = sodexhoAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drSodexho);

                    //CreditCard Amount
                    tmpValue = 0d;

                    if (dsResult.Tables[5].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[5].Rows[0]["CreditCardAmount"].ToString(), out tmpValue))
                            creditCardAmt = tmpValue;
                    }

                    DataRow drCard = dsResult.Tables[0].NewRow();
                    drCard[1] = "CREDITCARD AMOUNT";
                    drCard[3] = creditCardAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drCard);

                    //Get Advances & Bill from Salaries Application
                    salariesAmt = DBHelper.GetEmpAdvancesandBillsForMonth(fromDate, toDate, cmbHBranch.SelectedValue.ToString());

                    DataRow drSalariesApp = dsResult.Tables[0].NewRow();
                    drSalariesApp[1] = "EMP ADVANCES/BILLS";
                    drSalariesApp[3] = salariesAmt.ToString();
                    dsResult.Tables[0].Rows.Add(drSalariesApp);

                    if (dsResult.Tables[6].Rows.Count > 0)
                    {
                        if (double.TryParse(dsResult.Tables[6].Rows[0]["CreditNoteAmount"].ToString(), out tmpValue))
                            creditNoteAmount = tmpValue;
                    }

                    //Credit Note Amount
                    DataRow drCreditNoteAmount = dsResult.Tables[0].NewRow();
                    drCreditNoteAmount[1] = "CREDIT NOTES AMOUNT";
                    drCreditNoteAmount[3] = creditNoteAmount;
                    dsResult.Tables[0].Rows.Add(drCreditNoteAmount);

                    //Available Cash
                    DataRow drAvailableCash = dsResult.Tables[0].NewRow();
                    drAvailableCash[1] = "AVAILABLE CASH";
                    drAvailableCash[3] = Math.Round(totalSales - discounts - expenseAmt - sodexhoAmt - creditCardAmt - salariesAmt, 2);
                    dsResult.Tables[0].Rows.Add(drAvailableCash);

                    dgvHalfReport.DataSource = dsResult.Tables[0];
                    dgvHalfReport.Columns[0].Width = 80;
                    dgvHalfReport.Columns[1].Width = 170;
                    dgvHalfReport.Columns[2].Width = 70;
                    dgvHalfReport.Columns[3].Width = 100;

                    lblPOSSalesHalf.Text = "POS Sales: " + dsResult.Tables[1].Rows[0]["POSSales"].ToString();
                    lblCakeSalesHalf.Text = "Cake Sales: " + cakeSales.ToString();
                    lblDiscountHalf.Text = "Discount: " + discounts.ToString();
                    lblTotalSalesHalf.Text = "Total Sales: " + (totalSales - discounts + creditNoteAmount).ToString();
                    lblExpensesHalf.Text = "Expenses: " + expenseAmt.ToString();
                    lblSodexhoSalesHalf.Text = "Sodexho Sales: " + sodexhoAmt.ToString();
                    lblCardSalesHalf.Text = "Card Sales: " + creditCardAmt.ToString();
                    lblEmpAdvanceBillHalf.Text = "Emp Advance/Bill Amounts: " + salariesAmt.ToString();
                    lblCreditNoteAmountHalf.Text = "Credit Note Amount: " + creditNoteAmount.ToString();
                    lblCashAvailableHalf.Text = "Cash Available: " + Math.Round((totalSales - discounts - expenseAmt - sodexhoAmt - creditCardAmt - salariesAmt), 2).ToString();
                    lblBulkOrdersHalf.Text = "Bulk Orders: " + Math.Round(bulkOrdersAmt, 2).ToString();
                }
                else
                {
                    dgvHalfReport.DataSource = null;
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                dgvHalfReport.DataSource = null;
                lblPOSSalesHalf.Text = "POS Sales: ";
                lblCakeSalesHalf.Text = "Cake Sales: ";
                lblDiscountHalf.Text = "Discount: ";
                lblTotalSalesHalf.Text = "Total Sales: ";
                lblExpensesHalf.Text = "Expenses: ";
                lblSodexhoSalesHalf.Text = "Sodexho Sales: ";
                lblCardSalesHalf.Text = "Card Sales: ";
                lblEmpAdvanceBillHalf.Text = "Emp Advance/Bill Amounts: ";
                lblCreditNoteAmountHalf.Text = "Credit Note Amount: ";
                lblCashAvailableHalf.Text = "Cash Available: ";
                lblBulkOrdersHalf.Text = "Bulk Orders: ";
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnPrintHalf_Click(object sender, EventArgs e)
        {
            if (dgvHalfReport.DataSource != null)
            {
                PrintDGV.Branch = Branch;
                PrintDGV.ReportType = "Half Yearly Report";
                PrintDGV.Print_DataGridView(dgvHalfReport);
            }
        }

        #endregion

        private void btnLogin_Click(object sender, EventArgs e)
        {

        }

        private void txtPassword_KeyUp(object sender, KeyEventArgs e)
        {

        }

        private void btnLoginUser_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtUserNameUser.Text.Trim().ToLower() == "ksbakers.counterreports" || txtPasswordUser.Text.Trim().ToLower() == "reports." + DateTime.Now.ToString("ddMMyyyy"))
                {
                    IsLoggedIn = true;
                    tabMainCtrl.SelectTab(0);
                    return;
                }
                else
                {
                    MessageBox.Show("Invalid Details", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtPasswordUser.Clear();
                    txtPasswordUser.Focus();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtPasswordUser_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btnLoginUser_Click(sender, e);
        }

        private void btnMain_Click(object sender, EventArgs e)
        {
            tabMainCtrl.SelectTab(0);
        }
    }
}